Search code examples
javaguavaevent-bus

Google Guava EventBus and Exceptions in Event Handlers


the Guava EventBus documentation says that "handlers should not, in general, throw. If they do, the EventBus will catch and log the exception. This is rarely the right solution for error handling and should not be relied upon; it is intended solely to help find problems during development."

If you know that certain exceptions might occur you can register a SubscriberExceptionHandler with the EventBus and use it to handle these exceptions.

But what happens if an unhandled exception occurs? Normally, I would want an unhandled exception to "bubble up" the calling chain. When using a SubscriberExceptionHandler, I have access to the original exception that was thrown in the event handler, and I just want to rethrow it. But I could not figure out how.

So how can you make sure unexpected exceptions in event handlers are not "swallowed", regardless if a SubscriberExceptionHandler is used or not?

Any help would be greatly appreciated.


Solution

  • If you want to deal with unchecked exceptions, you could implement SubscriberExceptionHandler's method like this:

    public void handleException(Throwable exception, SubscriberExceptionContext context) {
        // Check if the exception is of some type you wish to be rethrown, and rethrow it.
        // Here I'll assume you'd like to rethrow RuntimeExceptions instead of 'consuming' them.
        if (exception instanceof RuntimeException) {
            throw (RuntimeException) exception;
        }
    
        // If the exception is OK to be handled here, do some stuff with it, e.g. log it.
        ...
    }
    

    After creating a class implementing the SubscriberExceptionHandler interface, you can pass its instance to the EventBus's constructor:

    EventBus eventBus = new EventBus(new MySubscriberExceptionHandler());
    

    And done, eventBus will use your exception handler which will let RuntimeExceptions bubble up.