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.
If you want to react differently (in code) depending on what caused the exception (either invalid name or invalid id) then I would suggest having different exceptions.
If not, then you don't even need the getErrorCode()
method, you can just add the error code to the message of the exception and the exception will give you all the information you need for debugging.