简体   繁体   English

从函数返回错误的最佳实践是什么?

[英]What are the best practices for returning errors from functions?

I usually do something like the example below when I need to return error messages from a function, if no errors occur I just return an empyty string. 当我需要从函数返回错误消息时,通常会执行以下示例中的操作,如果没有错误发生,我只会返回一个空字符串。 Is this best practice, or are there alternatve ways of returning error messages from functions? 这是最佳实践,还是有从函数返回错误消息的替代方法?

Function Test() as String
  ' Do something
  If error occured Then   
    Return "Some error message"
  Else   
    Return ""    
End Functon

Instead of returning an error message you should throw an exception that contains the error message. 而不是返回错误消息,您应该引发包含错误消息的异常。

Here's a quick overview: http://www.vbdotnetheaven.com/UploadFile/rajeshvs/dotnetException04162005022135AM/dotnetException.aspx 快速概览: http : //www.vbdotnetheaven.com/UploadFile/rajeshvs/dotnetException04162005022135AM/dotnetException.aspx

Exception Handling is the preferred method for dealing with errors. 异常处理是处理错误的首选方法。 Error code return values can be obliviously ignored by developers using your functions. 开发人员使用您的函数可以忽略错误代码的返回值。 Exceptions force them to take notice. 异常迫使他们引起注意。 It's definitely worth learning about. 绝对值得学习。

When you wrote the code in your question, you probably assumed that it would be called like this: 当您在问题中编写代码时,您可能假设它的名称如下:

String message = Test();
// process the message for errors.

A lot of developers will just bypass processing the message, or even call your function like this: 许多开发人员只会绕过消息处理,甚至像这样调用您的函数:

Test();
// go about your business, happily ignoring the error message

If your code throws an exception instead, it cannot be ignored. 如果代码抛出异常,则不能忽略它。 A developer has to at least acknowledge that an exception is thrown by putting a try block around your function call. 开发人员必须至少通过在函数调用周围放置try块来确认抛出了异常。 At that point they're forced to do something with it. 在那时,他们被迫为此做些事情

As Erik and Bill have said, exceptions are the normal way of propagating errors in .NET. 正如Erik和Bill所说,异常是.NET中传播错误的常规方法。 However, there are situations where they're not appropriate - such as validating user input. 但是,在某些情况下它们不合适(例如验证用户输入)。 At that point there are a couple of alternatives: 到那时,有两种选择:

  • Use an error code (eg an enum) to indicate the type of mistake. 使用错误代码(例如,枚举)指示错误的类型。 For instance, you might have one code for "Password was too short" and another for "Password didn't contain any numbers" etc. 例如,您可能有一个代码“密码太短”而另一个代码“密码不包含任何数字”等。

  • Use an error message in the way that you've suggested in the question. 按照问题中的建议使用错误消息。 I would personally use a null reference for the "it was okay" case or possibly make the method return a Boolean value (valid/invalid) and have an out parameter for the error message. 我个人会使用空引用来表示“还可以”,或者可能使该方法返回布尔值(有效/无效),并为错误消息提供out参数。 Using a string is lousy for internationalisation, but is simpler in many ways (avoids extra lookups, easier to add a new kind of error etc) than the error code version. 使用字符串对于国际化来说很糟糕,但是比错误代码版本在许多方面(避免额外的查找,更容易添加新的错误等)更简单。 That may well be fine for an internal app which will never need to be internationalised. 对于永远不需要国际化的内部应用程序来说,这可能很好。

I stress that these are only options where exceptions don't make sense - otherwise, exceptions are the way to go. 我强调,这些只是例外没有意义的选择-否则,例外是解决之道。

A Request-Response pattern can help with handling errors and the many ways something might fail. 请求-响应模式可以帮助您处理错误以及某些可能导致失败的方式。 For example, in a credit card authentication procedure you might have: 例如,在信用卡身份验证过程中,您可能具有:

class CreditCardAuthenticationRequest {
    string CreditCardNumber;
    string FullName;
    ...
}

class CreditCardAuthenticationResponse {
    CreditProcessorStatusCode Status;
    CreditProcessorWarnings[] Warnings;
    CreditProcessorErrors[] Errors;
    Exception Exception;
    ...
}

Now suddenly all your error handling and validation can be contained in a neat little package. 现在突然所有的错误处理和验证都可以包含在一个简洁的小程序包中。 The Patterns in Action sample application from DoFactory.com uses this extensively. DoFactory.com的Patterns in Action示例应用程序广泛使用了此功能。

I would agree that, in general, you would want to use exceptions for errors when the method would not otherwise return a value. 我同意,通常,当该方法不返回值时,您将希望对错误使用异常。 If the method does return a value, however, you can and perhaps should use the return value in certain circumstances. 但是,如果该方法确实返回了一个值,则在某些情况下您可以并且应该使用该返回值。 For example, if you are attempting to retrieve an object from a keyed collection and the key doesn't exist, it's perfectly reasonable to return null as evidence of non-existence rather than throwing an exception. 例如,如果您尝试从一个有键集合中检索一个对象而该键不存在,则完全合理地返回null作为不存在的证据,而不是抛出异常。 Your case doesn't seem to fit this scenario, however, and I would go with the exception. 但是,您的情况似乎不适合这种情况,我会例外。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM