Can I use the observer pattern to handle errors?

Can the observer pattern be used to handle errors? What are its advantages and disadvantages? Does anyone 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();**
.....
}
}

      

+3


source to share


3 answers


You will most likely 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 a fairly common approach: you register a callback method that should be notified when an exception occurs. However, this is not strictly Observer - the state of the target has not changed, you are only notified of the error that occurred in the target (which, on the other hand, is a kind of event).

You can also usually have more than one observer. It's rare to have more than one error handler, but it's not hard to imagine.

+6


source


Observer pattern can be used for message ... Something catches an error condition and emits an ErrorEvent, something else reports the error to the log or control system. This is quite common.

However, consider the main flow of your code: you probably need to go different ways

fetch customer details
if customer is a good credit risk
    lend them some money

      

what does your code do if client data cannot be retrieved due to an error? By concept, you need



fetch customer details
if the fetch worked AND customer is a good credit risk
    lend them some money

      

there is some level of direct causality in the absence of error. We can implement this through exception handling or error checking, but we do it anyway, we need to really REFRECT the error in our logic.

Now you can create a more event-driven system in which everything happens in response to events. In this case, everything, not just error handling, is done using the Observer pattern.

+2


source


The observer pattern looks promising if you have one of the following options (or both):

  • We have one source that detects errors and issues error notifications. Then you need to allow other (unknown) components to receive these notifications.
  • We have one central component that can handle error notifications and wants it to listen to other (unknown) components that generate error notifications.

In other cases, we can find projects that fit better.

+2


source







All Articles