在google guava eventbus中显示异常

a64a0gku  于 2021-07-03  发布在  Java
关注(0)|答案(1)|浏览(411)

googleguavaeventbus接受异常并记录它们。
我编写了一个非常简单的应用程序来解释我的方法:

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!");
    }
  }
}

这是永远不会到捕捉块!
所以我添加了一个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);
        }
    });

它允许我在处理程序内部处理异常,但我的要求是将异常带到顶层,在顶层处理它们。
编辑:我在一些网站上找到的一个旧的解决方案(这与Guavav18有关)

public class CustomEventBus extends EventBus {
@Override
void dispatch(Object event, EventSubscriber wrapper) {
    try {
        wrapper.handleEvent(event);
    } catch (InvocationTargetException cause) {
        Throwables.propagate(Throwables.getRootCause(cause));
    }
 }
}
vsaztqbk

vsaztqbk1#

以下技巧对我很有效:
最新的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));
  }
}

相关问题