Do you think it is ok to use error codes within exception to specify error type? Please take a look on this code:
public class MyException extends Exception {
public static final String ERROR_CODE_INVALID_NAME = "";
public static final String ERROR_CODE_INVALID_ID = "";
...
private String errorCode;
public MyException(String message, String errorCode) {
super(message);
this.errorCode = errorCode;
}
public String getErrorCode() {
return errorCode;
}
}
I know that it is better to use enum instead of Strings in this example, but I'm actually concerned about the concept of error codes. Do you think exceptions hierarchy would be better here? I can't find any authoritative source that says error codes within exception is anti-pattern. Thx.
The Exception class is used for exception conditions that the application may need to handle. Examples of exceptions include IllegalArgumentException, ClassNotFoundException and NullPointerException. The Error class is used to indicate a more serious problem in the architecture and should not be handled in the application code.
The class at the top of the exception class hierarchy is the Throwable class, which is a direct subclass of the Object class. Throwable has two direct subclasses - Exception and Error. The diagram below shows the standard exception and error classes defined in Java, organized in the Java exceptions hierarchy:
Refer to the diagram given below to understand the hierarchy of exceptions in Java along with their category of checked and unchecked exceptions: The above diagram shows the two types of exceptions, checked and unchecked, based on the time of occurrence, i.e. compile-time or run-time.
Examples of exceptions include IllegalArgumentException, ClassNotFoundException and NullPointerException. The Error class is used to indicate a more serious problem in the architecture and should not be handled in the application code.
Error codes are useful when
So, most time, I don't see any added value in error codes. I prefer an exception hierarchy or at least clear error message that are really useful, when found in a logfile (even 2 years after the programmer has left the company).
If you have requirements for error codes - the solution is not bad. Consider collecting all error codes in a central repository (a properties file) so that you can exchange the complete set easily:
myexception.ERROR_CODE_INVALID_NAME=text or number
myexception.ERROR_CODE_INVALID_ID=text or number
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