0

I am trying to setup a global exception handler in my application. When I trigger a NullpointerException by clicking a button for example, only the DefaultErrorHandler interacts with it and prints the stacktrace to my console.

What am I doing wrong?

Sadly, none of the ways detailed in the documentation (Custom Error Handler or Custom Exception Handlers) seem to work for me.

@Tag(Tag.DIV)
public class CustomErrorHandler extends Component implements HasErrorParameter<NullPointerException> {

  @Override
  public int setErrorParameter(BeforeEnterEvent event,
      ErrorParameter<NullPointerException> parameter) {
    System.out.println("custom error handler caught NPE");
    return 0;
  }
}
public class CustomErrorHandler implements ErrorHandler {

  private static final Logger log = logger(CustomErrorHandler.class);

  @Override
  public void error(ErrorEvent errorEvent) {
    log.error("Something wrong happened", errorEvent.getThrowable());
    if(UI.getCurrent() != null) {
      UI.getCurrent().access(() -> {
        Notification.show("An internal error has occurred." +
            "Please contact support.");
      });
    }
  }
}

which is initialized in

@SpringComponent
public class ServiceListener implements VaadinServiceInitListener, SessionInitListener {

  @Override
  public void serviceInit(ServiceInitEvent event) {
    event.getSource().addSessionInitListener(this);
  }
  @Override
  public void sessionInit(SessionInitEvent event) throws ServiceException {
    event.getSession().setErrorHandler(new CustomErrorHandler());
  }
}

EDIT: I found out that it works if exceptions are caught and re-thrown.

button.addClickListener(it -> { 
  try {
    doSomeStuffProducingExceptions();
  } catch (Exception e) {
    throw e;
  }
});
Kocht
  • 1
  • 2

1 Answers1

1

Yes, ErrorHandler implementations work only for exceptions generated inside event handlers. Read this for more details: https://mvysny.github.io/vaadin-error-handling/

EDIT: Some interesting statements of the above linked article: "There are two main entrypoints of error handling in Vaadin:

  1. The router exception handling, triggered during the navigation phase when the view is constructed, and
  2. Session’s ErrorHandler, triggered after the view has been rendered."

"The ErrorHandler takes effect after the navigation is complete and the view is fully displayed. It handles exceptions coming from:

  1. Button click listeners, or generally any events coming from components.
  2. Asynchronous blocks run via UI.access()"

"Note: It’s not possible to use one unified solution, for example only have an ErrorHandler handling the routing exceptions."

It caused a problem to me as well, because an exception was thrown in the constructor, after navigation and before the rendering of the view is completed. I cannot find an elegant solution for this scenario.