Wednesday, 26 February 2014

Defining your own exception types

I'm in a habit of creating different classes for different exceptions, as opposed to for example using RuntimeException-s or IllegalStateException-s describing details as a string in the constructor. I'm not hundred percent sure that's an ultimately better practice and recently I've watched a talk where the speaker adviced against class proliferation. True, in a language like Java, creating classes is very boilerplate. In Scala an exception class is probably half a line of code, and you can stuff a dozen in the same source file.
But, yesterday I realized there is a situation where a custom exception class comes handy. Imagine you put some validation logic in your domain class.
public class PlayerId {
    private final String id;
    public PlayerId(String id) {
        Validate.notNull(id); 
        this.id = id;
    }
}

The Validate can be a validator class from Apache Commons or some custom class you wrote throwing IllegalArgumentException-s. At the project I'm working on right now we are using messaging and ActiveMQ as the integration solution. If there is an exception, the message is bounced back to the queue and the broker retries to deliver it a couple of times before it gives up and puts the message in the Dead Letter Queue. So if the message had a null as a player id, no matter how many times the broker retries it will always fail, but in the meantime the process consumes time and threads, possibly generating the same error log for a number of times. Instead of this if you create a( possibly abstract) n custom exception for domain problems, like

public abstract class DomainException extends RuntimeException {
    public DomainException(String msg) {
        super(msg);
    }
}

And at the entry point of your system you do a try-catch for it
try {
     // do the real thing
} catch(DomainException ex) {
    //do something, e.g. logging
}

Then you can catch and handle the problems where there is no chance of recovery in retrying.

No comments :

Post a Comment