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 楼答案
目前,这是一个经过深思熟虑的决定,并在EventBus文档中进行了讨论:
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.
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);
}
}
# 1 楼答案
这里是懒惰的代码
现在,您可以订阅
ExceptionEvent
这是我的
ExceptionEvent
,仅供复制&;粘贴# 2 楼答案
目前,这是一个经过深思熟虑的决定,并在EventBus文档中进行了讨论:
替代解决方案是being considered,尽管我严重怀疑它们能否进入第12版
# 3 楼答案
只需继承guava EventBus,并编写自己的自定义EventBus。 提示:这个类应该用com编写。谷歌。常见的eventbus包,以便可以覆盖内部方法