我使用 guava 的 EventBus,不幸的是它捕获并记录了事件处理程序抛出 RuntimeException 时发生的 InvocationTargetException。我可以禁用此行为吗?
问问题
3070 次
3 回答
8
就目前而言,这是一个深思熟虑的决定,并在 EventBus 文档中进行了讨论:
一般来说,处理程序不应该抛出。如果他们这样做了,EventBus 将捕获并记录异常。这很少是错误处理的正确解决方案,不应依赖;它仅用于帮助在开发过程中发现问题。
正在考虑替代解决方案,尽管我严重怀疑它们是否会进入第 12 版。
于 2012-02-10T20:00:18.920 回答
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;
}
}
于 2014-10-30T02:28:37.670 回答
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);
}
}
于 2016-11-29T03:24:30.757 回答