2016-05-10 44 views
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)); 
    } 
} 
} 

回答

3

下面的技巧的作品對我說:

最新EventBus類呼籲handleSubscriberException()您需要在您的擴展EventBus類重寫的方法: (這裏我有包括這兩種解決方案中,只有一個會爲您當前的版本)

public class CustomEventBus extends EventBus { 
    //If version 18 or bellow 
    @Override 
    void dispatch(Object event, EventSubscriber wrapper) { 
    try { 
     wrapper.handleEvent(event); 
    } catch (InvocationTargetException cause) { 
     Throwables.propagate(Throwables.getRootCause(cause)); 
    } 
    } 
    //If version 19 
    @Override 
    public void handleSubscriberException(Throwable e, SubscriberExceptionContext context) { 
    Throwables.propagate(Throwables.getRootCause(e)); 
    } 
} 
+0

的方法對18級以下只適用,如果你把類CustomEventBus在包com.google.common.eventbus(EventSubscriber是包PRIVA TE)。 –