Custom Error Handling

You can customize the error views related to navigation between different routes as described in the Router Exception Handling article.

For other unhandled runtime exceptions, an ErrorHandler class can be used to gracefully let users know that something went wrong. In order to do so, first create your custom ErrorHandler class, then use that class to override the default error handler.

For example, the following CustomErrorHandler class logs the error and displays a friendly notification to the user.

public class CustomErrorHandler implements ErrorHandler {

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

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

Then assign the custom error handler to the current user session:

VaadinSession.getCurrent().setErrorHandler(new CustomErrorHandler());

To apply the custom error handler to all user sessions, you can use a SessionInitListener, which receives an event each time a new VaadinSession is initialized. See the Session and UI Listeners article to learn how to create a SessionInitListener.