Multiple error handlers

Hi,

The project I’m working on already has a “custom” error handler but I have a task to make another one which handles only one exception. My question is can the two handlers co-exist and if yes - where do I set mine to be used by the project?

Hi,

You can set only one instance of
ErrorHandler
per UI. But you can implement a handler that
dispatches
to other handlers according to the exception type. For example:

[code]
public class ErrorHandlerDispatcher implements ErrorHandler {

public interface CustomErrorHandler extends ErrorHandler {
    boolean canHandle(Class<? extends Throwable> throwableClass);
}

private static List<CustomErrorHandler> handlers = new ArrayList<>();

static { // add all the implementations
    handlers.add(new ErrorHandler1());
    handlers.add(new ErrorHandler2());
    handlers.add(new ErrorHandler3());
    handlers.add(new DefaultErrorHandler());
}

@Override
public void error(ErrorEvent event) {
    handlers.stream()
            .filter(handler -> handler.canHandle(event.getThrowable().getClass()))
            .findFirst()
            .ifPresent(h -> h.error(event));
}

}
[/code]You can create multiple implementations and add them to the
handlers
list. For example, if you want
ErrorHandler1
to handle only
NumberFormatException
s, you can implement it as follows:

public class ErrorHandler1 implements ErrorHandlerDispatcher.CustomErrorHandler {

    @Override
    public boolean canHandle(Class<? extends Throwable> throwableClass) {
        return throwableClass.equals(NumberFormatException.class);
    }

    @Override
    public void error(ErrorEvent event) {
        Notification.show("Number format exception!", Notification.Type.ERROR_MESSAGE);
    }
}