最佳实践方法,以表明服务器请求已经失败了? [英] Best Practice way to indicate that a server request has failed?

查看:98
本文介绍了最佳实践方法,以表明服务器请求已经失败了?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写一个连接到它或者返回一个简单的成功的消息或失败的超过100个不同风格中的一种服务的API。

I am writing an API that connects to a service which either returns a simple "Success" message or one of over 100 different flavors of failure.

原本我以为编写发送到该服务的请求的方法,这样,如果它成功的方法返回不算什么,但如果失败,无论出于何种原因,它抛出一个异常。

Originally I thought to write the method that sends a request to this service such that if it succeeded the method returns nothing, but if it fails for whatever reason, it throws an exception.

我不介意这样的设计非常多,但另一方面就在今天我读约书亚·布洛克的的如何设计一个好的API和重要性,他说抛出异常,表示异常情况......不要强迫客户端使用例外控制流。 (和相反,不静默失败。)

I didn't mind this design very much, but on the other hand just today I was reading Joshua Bloch's "How to Design a Good API and Why it Matters", where he says "Throw Exceptions to indicate Exceptional Conditions...Don't force client to use exceptions for control flow." (and "Conversely, don't fail silently.")

另外,另一方面,我注意到的HttpWebRequest我使用似乎请求失败时抛出一个异常,而不是返回一个包含500内部服务器错误消息的响应。

On the other-other hand, I noticed that the HttpWebRequest I am using seems to throw an exception when the request fails, rather than returning a Response containing a "500 Internal Server Error" message.

什么是在这种情况下,报告错误的最好方式?如果我扔在每次失败的请求例外,我在大规模的痛苦在未来的某个时候?

What is the best pattern for reporting errors in this case? If I throw an exception on every failed request, am I in for massive pain at some point in the future?

编辑:非常感谢你好心迄今的反应。一些阐述:

Thank you very kindly for the responses so far. Some elaboration:


  • 这将给予客户在他们的应用程序中引用的DLL。

  • 使用的类似例子是 ChargeCreditCard(CreditCardInfo我) - 显然,当ChargeCreditCard()方法失败,这是一个巨大的交易;我只是不是100%肯定我是否应该停止presses或传递到客户端的责任。

  • it's a DLL that will be given to the clients to reference in their application.
  • an analogous example of the usage would be ChargeCreditCard(CreditCardInfo i) - obviously when the ChargeCreditCard() method fails it's a huge deal; I'm just not 100% sure whether I should stop the presses or pass that responsibility on to the client.

编辑第二个:
基本上我并不完全相信要使用的这两种方法:

Edit the Second: Basically I'm not entirely convinced which of these two methods to use:

try { 
ChargeCreditCard(cardNumber, expDate, hugeAmountOMoney);
} catch(ChargeFailException e) {
  // client handles error depending on type of failure as specified by specific type of exception
}

var status = TryChargeCreditCard(cardNumber, expDate, hugeAmountOMoney);

if(!status.wasSuccessful) {
    // client handles error depending on type of failure as specified in status   
}

例如。当用户试图收取信用卡,是卡被拒绝的真正的例外的情况?我在问这个问题摆在首位下降太远了兔子洞?

e.g. when a user tries to charge a credit card, is the card being declined really an exceptional circumstance? Am I going down too far in the rabbit hole by asking this question in the first place?

推荐答案

下面的事情要考虑短名单。虽然不是COM prehensive,我相信这些东西可以帮助你写出更好的code。底线:不一定察觉异常处理是邪恶的。相反,书写时他们,问自己:我得如何真正明白我解决这个问题?通常情况下,这将帮助你成为一个更好的开发。

Here's a short list of things to consider. While not comprehensive, I believe these things can help you write better code. Bottom line: Don't necessarily perceive exception handling as evil. Instead, when writing them, ask yourself: How well do I really understand the problem I am solving? More often than not, this will help you become a better developer.


  1. 将其他开发人员能够读呢?它可以合理的了解的由普通的开发?例如: ServiceConnectionException 与混乱 ServiceDisconnectedConnectionStatusException

  2. 在抛出异常的情况下,如何的例外的是环境?什么是来电者必须以实现该方法呢?

  3. 这是例外致命?可什么真正可以用这个异常做,如果它被捉住?线程终止,出现内存不足的..你不能做任何有用的东西。不要抓住它。

  4. 是异常混乱?比方说,你有一个名为方法汽车GetCarFromBigSt​​ring(desc字符串),它接受一个字符串,并返回一个对象。如果大多数用例为这个方法是生成从字符串对象,不抛出当无法从字符串确定例外。相反,这样写布尔TryGetCarFromBigSt​​ring的方法(desc字符串,走出汽车)

  5. 这可以很容易prevented?我可以检查东西,假设数组的大小或变量是否为空?

  1. Will other developers be able to read this? Can it be reasonably understood by the average developer? Example: ServiceConnectionException vs. a confusing ServiceDisconnectedConnectionStatusException
  2. In the case of throwing an exception, how exceptional is the circumstance? What does the caller have to do in order to implement the method?
  3. Is this exception fatal? Can anything really be done with this exception if it is caught? Threads aborting, out of memory.. you can't do anything useful. Don't catch it.
  4. Is the exception confusing? Let's say you have a method called Car GetCarFromBigString(string desc) that takes a string and returns a Car object. If the majority use-case for that method is to generate a Car object from that string, don't throw an exception when a Car couldn't be determined from the string. Instead, write a method like bool TryGetCarFromBigString(string desc, out Car).
  5. Can this be easily prevented? Can I check something, let's say the size of an array or a variable being null?

有关code可读性的缘故,让我们有可能来看看你的背景。

For code readability's sake, let's potentially take a look at your context.

bool IsServiceAlive()
{
   bool connected = false;  //bool is always initialized to false, but for readability in this context

   try
   {
      //Some check
      Service.Connect();
      connected = true;
   }
   catch (CouldNotConnectToSomeServiceException)
   {
      //Do what you need to do
   }

   return connected;
}

//or
void IsServiceAlive()
{
   try
   {
      //Some check
      Service.Connect();
   }
   catch (CouldNotConnectToSomeServiceException)
   {
      //Do what you need to do
      throw;
   }
}



static void Main(string[] args)
{
    //sample 1
    if (IsServiceAlive())
    {
       //do something
    }

    //sample 2
    try
    {
       if (IsServiceAlive())
       {
          //do something
       }
    }
    catch (CouldNotConnectToSomeServiceException)
    {
       //handle here
    }

    //sample 3
    try
    {
       IsServiceAlive();
       //work
    }
    catch (CouldNotConnectToSomeServiceException)
    {
       //handle here
    }
}

您可以在上面看到,在样品3追赶 CouldNotConnectToSomeServiceException 不一定产生任何更好的可读性如果上下文是一个简单的二进制测试。然而,这两种工作。这是不是真的有必要吗?是你的程序,如果您无法连接大清洗?如何关键的是不是真的?这些都是你需要考虑到帐户中的所有因素。这很难说,因为我们没有访问所有code的。

You can see above, that catching the CouldNotConnectToSomeServiceException in sample 3 doesn't necessarily yield any better readability if the context is simply a binary test. However, both work. But is it really necessary? Is your program hosed if you can't connect? How critical is it really? These are all factors you will need to take in to account. It's hard to tell since we don't have access to all of your code.

让我们来看看一些其他的选择,最有可能导致问题。

Let's take a look at some other options that most likely lead to problems.

//how will the code look when you have to do 50 string comparisons?  Not pretty or scalable.
public class ServiceConnectionStatus
{
     public string Description { get; set; }
}

//how will your code look after adding 50 more of these?
public enum ServiceConnectionStatus
{
   Success,
   Failure,
   LightningStormAtDataCenter,
   UniverseExploded
}

这篇关于最佳实践方法,以表明服务器请求已经失败了?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆