Search code examples
javaobserver-pattern

Can I use observer pattern for error handling?


Can I use observer pattern for error handling? What are adv/disadvantages of it? Does anybody use this approach for this purpose?

UPDATE:

class MyErrorApi{
public static final int NETWORK_ERROR = 1;

public(MyErrorApi error){
...
}
}


interface ErrorListener{
void onErrorOcurred(MyErrorApi arror)
}


class MyBaseScreen implements ErrorListener{


void onErrorOcurred(MyErrorApi arror){
swirch(arror){
**showPopup();**
.....
}
}

Solution

  • More likely you need a simple callback like ErrorHandler:

    public interface ErrorHandler {
    
        /**
         * Handle the given error, possibly rethrowing it as a fatal exception
         */
        void handleError(Throwable t);
    
    }
    

    This is quite common approach - you register a callback method to be notified when exception occurs somewhere. However this is not strictly an Observer - the state of the target object didn't change, you are only notified about an error that occurred in the target (which, on the other hand, is kind of event).

    Also typically you can have more than one Observer. It is rare to have more than one error handler, but not hard to imagine.