In vaadin 8 when an application error occurred it was possible to treat it, I did it like this:
1 - I created an extended class of DefaultErrorHandler
2 - In the UI I set this class, with the code setErrorHandler(new ExceptionHandler());
3 - If an error occurred, for example an unsuccessful calculation: int x = 5/0;, automatically the Error Handling class I created sent me this problem, showed a message to the user and life went on (he could continue to use other functions without even having to refresh the page).
In vaadin 14, there is nothing in the documentation about errors, only about route errors (which is a different situation).
How to do this in Vaadin 14 LTS?
I tried to set the class or even catch the error like this: VaadinSession.getCurrent().SetErrorHandler. But it doesn’t work, when the error happens the whole stack of the error appears to the user, making it impossible to use from there.
None of the answers was accepted by the questioner and with good reason, I checked all of them and I was also not successful in any of the approaches.
We have the same difficulty, we want to handle a UI error and not a route error.
Strange this difficulty, the handling of UI errors is a little basic, because no matter how hard we try not to present an error, it happens and must be treated in an elegant way and especially not to end the user’s use. Redirecting to another route is not feasible, as it would lose everything the user has done in the UI.
In vaadin 8 it was so simple: setErrorHandler(new ExceptionHandler());
Create a error handler by implementing the com.vaadin.flow.server.ErrorHandler interface
public class CustomExceptionHandler implements ErrorHandler {
private static final Logger logger = LoggerFactory.getLogger(CustomExceptionHandler.class);
@Override
public void error(ErrorEvent errorEvent) {
//All important logic exceptions should have been caught before reaching this point.
//Exceptions reaching this are an indication something went really wrong
Throwable t = errorEvent.getThrowable();
logger.error("Uncaught UI exception", errorEvent.getThrowable());
if(UI.getCurrent() != null) {
UI.getCurrent().access(() -> {
Notification.show("We are sorry, but an internal error occurred? Please contact support.");
});
}
}
}
In the class that extends the VaadinServlet (with the @WebServlet annotation) we implemented the SessionInitListener interface and added the servlet as a sessioninitlistener by setting it on the service. You could also make a seperate class that implements the SessionInitListener if you want, as long as you create an instance of it and pass it to the service.