开发者

Best practice Error handling

I was wondering what would be the best way to handle errors in an application in programming languages like C++, Java, C#.

I thought of creating a place where to store number related to error and warning messages .

For example :

10000 -> "Can't read file". ... 20000 -> "Buffer overflow". ... 80000 -> "Critical stuff".

I think it's a good practice to map errors with numbers. It's easier to find the error no matter which lang开发者_如何学Cuages it's displayed with. What do you guys think about that ? Is there a even better way to do that ?

Another point is, how to store them, how to create them ?

Is a big general enum a good solution ? Do we have to store them in a database ? In a file ?

It should be :

  • Easy to find an error in the code (ie. from the number).
  • Easy to add a new error (not using the same error number twice can be tricky if there are not at the same place).

What do you guys think about all that ?

Thanks in advance for your help and advices!


Using error codes to identify exceptions is not a bad practice.

It can be very useful in a production environment to keep the log files shorter and also it can be used to internationalize error messages.

On the other hand, when developing, it can be annoying to received an error code instead of a full blown error message with meaningful description. A developer has to go and check what the error code is about.

In one of my projects (using Java) I have developed an hybrid approach. My root exception has a constructor that uses an Enum class. The Enum class contains a list of error codes + default error messages. Something like:

public enum ErrorCodes {

    VALIDATION_ERROR(5001, "One of the objects cannot be validated"),
    RESOURCE_NOT_FOUND(4004, "The requested resource does not exist"),

The root exception has also other constructors, so that a developer can override the default message:

public CoreException(ErrorCodes _errorCode, final String message, final Throwable cause) {
   super(message, cause);
   errorCode = _errorCode.getCode();
}


public CoreException(ErrorCodes _errorCode, final String message) {
   super(message);
   errorCode = _errorCode.getCode();
}

When the exception is caught the Exception handler can decide (based on some configuration setting) to log the error and the message or the error only. A more sophisticated error handler could also look up a message in a specific language from a resource bundle based on the error code.


Do not do it.

We've got better tools than C and FORTRAN.

Throw exceptions and give the names. C# and Java will give call stacks.

C++ can tell you the type of the exception (just barely)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜