Error codes within exception vs exceptions hierarchy

Darkoboar picture Darkoboar · Feb 15, 2012 · Viewed 30.9k times · Source

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.

Answer

Andreas Dolk picture Andreas Dolk · Feb 15, 2012

Error codes are useful when

  • you can't display a complete error message (dish washer display)
  • the code has to be processed internally (some logic is triggered if a certain code appears or a server sends an error code to the client while the client is responsible for the message)
  • we have a great manual and the user can use the code to get comprehensive information
  • The user does not need to know, what happend, but has to contact the vendor

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