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 languages 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 :
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With