Let\'s say I have a method that throws an Exception of some kind. The exception-throwing code lies in a third-party library that access an external service. I have a few cla
Thanks for the help, all. I looked into Spring AOP, but ultimately decided against it. I wound up using try/catch blocks, but creating a handler that is injected into each class and wrapping any thrown exceptions in my own exception class, then passing that to the handler in a single line. It's a bit similar to the suggestion by user2511414 in that there's a dedicated handler, but I gave up on annotations. I have a good number of try/catch blocks, but at least I've kept the majority of the handling logic out. A quick rundown of my solution in case other folks find this, which is a bit obfuscated, but you can still get the point:
public enum DoThisEnum {
DO_THIS,
DO_THAT,
DO_OTHER_THING;
}
public class MyException extends Exception {
private DoThisEnum doThis;
private MyObject dataObj;
//Constructor, overloaded to run super(originalException) or super()
//as well as taking doThis and dataObj as parameters
//Getters, setters, etc
}
public interface IExceptionHandler {
void handleException(MyException exception);
}
Then implement the IExceptionHandler with a concrete class that takes MyException, reads out the additional data, and performs actions based on it. Then each block that might throw such an exception can be caught like so:
...
try {
doSomething(Object data);
} catch (SomeException e) {
handler.handleException(new MyException(e, DoThisEnum.DO_THAT, data));
//Anything else to do, maybe return or return null, rethrow, etc.
}
Now most of the nitty-gritty is encapsulated in the handler and the try/catch blocks are minimal. The handler can log the stack trace of the original exception, maybe do other things based on it, and then perform your own actions based on the enum. Maybe it isn't the perfect solution, but it works well enough here.