I am having difficulty deciding how to implement an exception handling strategy.
I am using an observer pattern to allow "plugin" programmers to subscribe to Message
s. These subscribers generally log a unique error (and do some other stuff) under an exceptional circumstance during handling the message. The code snippet below is an example of what a common implementation (and its interface) looks like:
// API interface
interface IMessageListener {
void onMessage(Message m);
}
class StuffMessageListener implements IMessageListener {
...
@Override void onMessage(Message m) {
try {
Stuff s = stuffDAO.getStuff(..); // throws SQLException
...
m.reply(true);
} catch (SQLException e) {
// if an exception happens, log it, and reply to the message
log.error(A_UNIQUE_ERROR_CODE, e);
m.reply(false);
}
}
}
What irks me is that the catch block has become very redundant code, copied throughout 95% of the ~50 existing listeners. Can we come up with something better?
A good solution should:
UPDATE:
Thanks everyone for your answers. I wanted to mention that there is a subtle requirement needed for the solution. The UNIQUE_ERROR_CODE
should be unique across all declarations of the listeners. That way, I could gain statistics based upon where the error was caught across all listeners.
If the UNIQUE_ERROR_CODE
is buried underneath an abstract class, or is used outside onMessage(..)
, I will lose the needed "uniqueness."
m.reply(boolean)
do? – Nick ODell Aug 1 '12 at 17:40suppressReply()
method, but I'm not sure how much I like that.. The reason for this new method is because in some cases, the message should not be replied to. – Beefyhalo Aug 1 '12 at 17:47