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.
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