3
谷歌Guava EventBus吞下異常並僅記錄它們。引發Google Guava EventBus中的例外
我寫了一個非常簡單的應用來解釋我的方法:
public class SimplePrinterEvent {
@Subscribe
public void doPrint(String s) {
int a = 2/0; //This is to fire an exception
System.out.println("printing : " + s);
}
}
演示
public class SimplePrinterEventDemo {
public static void main(String[] args) {
EventBus eventBus = new EventBus();
eventBus.register(new SimplePrinterEvent());
try{
eventBus.post("This is going to print");
}
catch(Exception e){
System.out.println("Error Occured!");
}
}
}
這不會來catch塊!
因此,我添加了SubscriberExceptionHandler並覆蓋了handleException()。
EventBus eventBus = new EventBus(new SubscriberExceptionHandler() {
@Override
public void handleException(Throwable exception,
SubscriberExceptionContext context) {
System.out.println("Handling Error..yes I can do something here..");
throw new RuntimeException(exception);
}
});
它讓我處理處理程序中的例外,但我的要求是把該異常到頂層,在那裏我處理它們。
編輯:我在某些網站找到的舊解決方案。 (這與番石榴V18工作)
public class CustomEventBus extends EventBus {
@Override
void dispatch(Object event, EventSubscriber wrapper) {
try {
wrapper.handleEvent(event);
} catch (InvocationTargetException cause) {
Throwables.propagate(Throwables.getRootCause(cause));
}
}
}
的方法對18級以下只適用,如果你把類CustomEventBus在包com.google.common.eventbus(EventSubscriber是包PRIVA TE)。 –