Java – exceptions in Google guava eventbus and event handlers
The guava eventbus documentation illustrates this
If you know that some exceptions may occur, you can register the subscriberexceptionhandler with eventbus and use it to handle these exceptions
But what happens if an unhandled exception occurs? Usually, I want an unhandled exception to "bubble" the call chain When using subscriberexceptionhandler, I can access the original exception thrown in the event handler, and I just want to throw it again But I can't figure out how
So, how to ensure that unexpected exceptions in the event handler are not "swallowed up" regardless of whether the subscriberexceptionhandler is used or not?
Any help would be appreciated
Solution
If you want to handle unchecked exceptions, you can implement the method of subscriberexceptionhandler, as follows:
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 that implements the subscriberexceptionhandler interface, you can pass its instance to the constructor of eventbus:
EventBus eventBus = new EventBus(new MySubscriberExceptionHandler());
When finished, eventbus will use your exception handler, which will bubble runtimeexceptions