1

I have some basic ExceptionHandler view:

@ParentLayout(MainLayout.class)
@AnonymousAllowed
public class ExceptionHandler extends VerticalLayout implements HasErrorParameter<Exception> {

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

    @Override
    public int setErrorParameter(BeforeEnterEvent event, ErrorParameter<Exception> parameter) {

        logger.error("Error", parameter.getException());

        Label label = new Label(parameter.getException().getMessage());
        add(label);

        return HttpServletResponse.SC_NOT_FOUND;
    }

}

which works fine when error occurs in synchronous calls.

But when I use @Async feature, like for example:

    ListenableFuture<DecisionMatrixPage> listenableFuture = container.queryDataAsync();
    var ui = UI.getCurrent();
    listenableFuture.addCallback(page -> {

        ui.access(() -> {
            //do something
        });

    }, err -> {
        logger.error("Error", err);
        throw new AsyncException("Async error", err);
    });

I may only log the error but unfortunately rethrowing of AsyncException is not catched by ExceptionHandler view. How to properly re-throw exception to be catched by ExceptionHandler ?

alexanoid
  • 24,051
  • 54
  • 210
  • 410
  • 1
    Wouldn't that be quite aggressive to use the same handler async? The user might be somewhere in your app and unless the exception now prevents any further work, the user could just continue and check out the problem later. I'd rather handle the error dedicated for this case (e.g. show a notification). – cfrick Oct 13 '22 at 06:20
  • Thanks, yes, you are right. I'll implement async error handling dedicated for each separate case to notify the user – alexanoid Oct 13 '22 at 08:03

1 Answers1

4

View implementing HasErrorParameter is used only when exception occurs during navigation. For more general exception handler you need to setup ErrorHandler using VaadinSession#setErrorHandler. The right place to setup the error handler is usually in the session init listener.

https://vaadin.com/docs/latest/advanced/session-and-ui-init-listener

Tatu Lund
  • 9,949
  • 1
  • 12
  • 26