Related to: Is onError handler better than exceptions?
I am writing a piece of library code that performs certain tasks, to separate concerns, we decided it should not write to a log or write to the display directly, but instead provide an event registration mechanism that allows interested client code to listen to events of its life-cycle.
So far so good. We have an event handler for log, and and event handler for display, they are informed when an event occurs and they write to the log / display independently.
So we have so far (pseudo code)
class MyLib(List<MYLibEventHandler> listeners) class Display implements MYLibEventHandler class Log implements MYLibEventHandler
The question that was raised was - how to inform the clients of exceptions? One way of looking at it is that an exception can be looked as just another event. It is something external that happens, and the clients are interested in knowing when it occurs.
So we can simply add another event for exceptions that receives the exception object. (we can re-throw the exception to allow any other try / catch constructs to handle it, but the log / display are not really handling the exception, they are just being notified it happened so they can do whatever they want with it. They can't really recover from it)
On the other hand, it smells wrong. An exception is not a normal event, it's a break in the flow, so we can say that our "main" will catch any exceptions and pass it to the
Log instances explicitly, outside of the event dispatch mechanism.
This smells also, because we already have a list of listeners, yet we explicitly call the log and the display to handle the exception.
(Perhaps I should not be alarmed that the code is doing something "exceptional" when handing an "exception". but it still smells that I need to keep track of clients twice)
So I'm stuck with a code smell no matter what I choose.
Is there a design pattern to handle multiple listeners / handlers for the same exception? try catch is very "single listener" / "hierarchical" structure, it doesn't seem the right tool for a wide "dispatch" like scenario. Perhaps some sort of an AOP pattern?
My attempt to answer this is that if I have a remote server, with multiple clients, and the server needs to communicate that a server exception occurred, there would be no question since the client can't really "try / catch" the exception. It will be more likely be sent as an event (e.g. in Akka as a Try object). Even in RMI, the exception is sent more as an "event" and only then triggers a
Is there a known design pattern to handle multiple, independent, read-only listeners for an exception (e.g. listeners that can't and won't recover from the exception, they just need to know it happened)
Perhaps in this case, sending the exception as an event (and then rethrowing it) is the right way to go?