Sunday, July 13, 2014

Exception - How to manage different exceptions your code wants to throw?

Often I have seen multiple Exception types created to handle different types of exceptions. In Java they all become individual classes. They might all extend from a common Exception class defined by you. But as Java does not support inheritance of constructors we end up having multiple classes with similar code. Not if it was Ruby code :)

Anyways. I got the following thought from the way Http defines Status Codes.

http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html

Define broad level Exception classes.

Informational, Success, Bad Request, Server Error. You may or may not have Redirection. In each of these Exception classes have status code. If possible, try to keep the status codes matching to the http status codes.

Now you have limited set of classes and you can set specific status code based on a scenario.

class InformationalException {
  public static enum InformationalStatus {
     // you have avoid it by using directly http status from commons client
  }

  public InformationalException(InformationalStatus status, String message, Throwable th) {
  }
}

The good news is most of the clients understand the http codes and it is no longer a magic.

Less code is less pain.