我使用guava的EventBus,不幸的是它捕获并记录了事件处理程序抛出RuntimeException时发生的InvocationTargetException。我可以禁用此行为吗?
答案 0 :(得分:8)
目前,这是一个深思熟虑的决定,并在EventBus文档中进行了讨论:
一般来说,处理程序不应抛出。如果他们这样做,EventBus将捕获并记录异常。这很少是错误处理的正确解决方案,不应该依赖;它仅用于帮助在开发过程中发现问题。
替代解决方案是being considered,但我严重怀疑它们会进入第12版。
答案 1 :(得分:4)
这是懒惰的代码
public class Events
{
public static EventBus createWithExceptionDispatch()
{
final EventBus bus;
MySubscriberExceptionHandler exceptionHandler = new MySubscriberExceptionHandler();
bus = new EventBus(exceptionHandler);
exceptionHandler.setBus(bus);
return bus;
}
private static class MySubscriberExceptionHandler implements SubscriberExceptionHandler
{
@Setter
EventBus bus;
@Override
public void handleException(Throwable exception, SubscriberExceptionContext context)
{
ExceptionEvent event = new ExceptionEvent(exception, context);
bus.post(event);
}
}
}
现在,您可以订阅ExceptionEvent
。
以下是我的ExceptionEvent
仅用于复制和粘贴
@Data
@Accessors(chain = true)
public class ExceptionEvent
{
private final Throwable exception;
private final SubscriberExceptionContext context;
private final Object extra;
public ExceptionEvent(Throwable exception)
{
this(exception, null);
}
public ExceptionEvent(Throwable exception, Object extra)
{
this(exception,null,extra);
}
public ExceptionEvent(Throwable exception, SubscriberExceptionContext context)
{
this(exception,context,null);
}
public ExceptionEvent(Throwable exception, SubscriberExceptionContext context, Object extra)
{
this.exception = exception;
this.context = context;
this.extra = extra;
}
}
答案 2 :(得分:0)
只需继承guava EventBus,并编写自己的自定义事件总线。 提示:此类应该在com.google.common.eventbus包中编写,以便可以覆盖内部方法。
package com.google.common.eventbus;
import com.google.common.util.concurrent.MoreExecutors;
public class CustomEventBus extends EventBus {
/**
* Creates a new EventBus with the given {@code identifier}.
*
* @param identifier a brief name for this bus, for logging purposes. Should be a valid Java
* identifier.
*/
public CustomEventBus(String identifier) {
super(
identifier,
MoreExecutors.directExecutor(),
Dispatcher.perThreadDispatchQueue(),
LoggingHandler.INSTANCE);
}
/**
* Creates a new EventBus with the given {@link SubscriberExceptionHandler}.
*
* @param exceptionHandler Handler for subscriber exceptions.
* @since 16.0
*/
public CustomEventBus(SubscriberExceptionHandler exceptionHandler) {
super(
"default",
MoreExecutors.directExecutor(),
Dispatcher.perThreadDispatchQueue(),
exceptionHandler);
}
@Override
void handleSubscriberException(Throwable e, SubscriberExceptionContext context) {
throw new EventHandleException(e);
}
}