Guava EventBus文档说明了这一点 “一般情况下,处理程序不应该抛出.如果这样做,EventBus将捕获并记录异常.这很少是错误处理的正确解决方案,不应该依赖它;它仅用于帮助在开发过程中发现问题. “
如果您知道可能发生某些异常,则可以使用EventBus注册SubscriberExceptionHandler并使用它来处理这些异常.
但是如果发生未处理的异常会发生什么?通常情况下,我希望一个未处理的异常“冒泡”调用链.使用SubscriberExceptionHandler时,我可以访问事件处理程序中抛出的原始异常,我只想重新抛出它.但我无法弄清楚如何.
那么,无论是否使用SubscriberExceptionHandler,如何确保事件处理程序中的意外异常不会被“吞噬”?
任何帮助将不胜感激.
如果要处理未经检查的异常,可以实现SubscriberExceptionHandler的方法,如下所示:
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.
...
}
在创建实现SubscriberExceptionHandler接口的类之后,您可以将其实例传递给EventBus的构造函数:
EventBus eventBus = new EventBus(new MySubscriberExceptionHandler());
完成后,eventBus将使用您的异常处理程序,它将使RuntimeExceptions冒泡.
网友评论