Vaadin 10+: How do I handle uncaught exceptions?

2.8k views Asked by At

In Vaadin 8:

UI.getCurrent().setErrorHandler(e -> handleError(e));

setErrorHandler does not exist in Vaadin 11, and I cannot find a corresponding method or documentation.

4

There are 4 answers

0
Martin Vysny On

In Vaadin 10+ there are two error handling entrypoints:

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

The former one is triggered when the server failed to produce a view because of an exception. The latter one is triggered by exceptions originating from button clicks, other kinds of component events, and by UI.access().

Please see https://mvysny.github.io/vaadin-error-handling/ for more details.

2
Tatu Lund On

In Flow (Vaadin 10+) there is a mechanism that catches uncaught exceptions in Router. So you can create error views, which are shown when defined exception is captured. They are created by implementing HasErrorParameter interface typed with the exception. Below is an example from Vaadin documentation:

@Tag(Tag.DIV)
public class RouteNotFoundError extends Component
        implements HasErrorParameter<NotFoundException> {

    @Override
    public int setErrorParameter(BeforeEnterEvent event,
            ErrorParameter<NotFoundException> parameter) {
        getElement().setText("Could not navigate to '"
                    + event.getLocation().getPath() + "'");
        return HttpServletResponse.SC_NOT_FOUND;
    }
}

I recommend to read more from the documentation.

https://vaadin.com/docs/v11/flow/routing/tutorial-routing-exception-handling.html

2
nemojmenervirat On

If you are using Vaadin Spring Boot starter implementation should look like this:

@SpringComponent
public class MyVaadinServiceInitListener implements VaadinServiceInitListener {

    @Override
    public void serviceInit(ServiceInitEvent event) {
        event.getSource().addSessionInitListener(e -> {
            e.getSession().setErrorHandler(errorEvent-> {
                Throwable t = errorEvent.getThrowable();
                // handle error
            });
        });
    }
}
3
Enver Haase On

There is VaadinSession::setErrorHandler for cases where it is not about an error that happens during routing / navigating but, for example, when clicking.