2016-05-10 41 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)。 –