A better way to define Java error codes

"Use enums instead of int constants" - This is one of the recommendations in the book "Effective Java". So what's wrong with int constants? Consider these error codes:

public static final int INVALID_REQUEST = 0;
public static final int MISSING_PARAMETER = 1;
public static final int MISSING_HEADER = 2;

Here are some limitations if you are using the int constants in your code.
  • There is no type safety since compiler will not complain if you pass the INVALID_REQUEST to a method which expects a different a error code, say MISSING_HEADER.
  • There is no namespace for int constants so there may be name clashes.
  • No way to translate constants to printable strings which is meaningful for a user.
The alternative is to use the "enum" type as shown below:

public enum MyExceptionCodes {
  INVALID_REQUEST(0, "The request is invalid"),
  MISSING_PARAMETER(1, "Required query parameter is missing"),
  MISSING_HEADER(2, "Required header is missing");

  private final int id;
  private final String msg;

  MyExceptionCodes(int id, String msg) {
    this.id = id;
    this.msg = msg;
  }

  public int getId() {
    return this.id;
  }

  public String getMsg() {
    return this.msg;
  }
}


Now you can use above enum, MyExceptionCodes, in your exception handling code.

public class MyException extends Exception {

  private int errorCode;
  private String errorMsg;

  public MyException(MyExceptionCodes code) {
    this.errorMsg = code.getMsg();
    this.errorCode = code.getId();
  }

  public int getErrorCode() {
    return errorCode;
  }

  public String getErrorMsg() {
    return errorMsg;
  }
}
Here is an example which shows how to use the error codes we just defined.

public class Test {
  public static void throwE() throws MyException {
    throw new MyException(MyExceptionCodes.MISSING_HEADER);
  }

  public static void main(String[] args ) {
    try {
      throwE();

    } catch (MyException e) {
      e.printStackTrace();
      System.out.println(e.getErrorMsg());
    }
  }
}

By using an enum type instead of int constants, you get compile time safety, name space protection, and easy conversion to a string representation. In addition, you can add rich methods to enhance your error codes. How about returning a link to an html page with the exception?

Comments

  1. Thank you for this brief tutorial! This helped me a lot in the process of making my own Exception class.

    ReplyDelete
  2. Excellent tutorial, well written and easy to use.

    ReplyDelete

Post a Comment