2012-02-10 67 views

回答

8

因爲它的立場,這是一個深思熟慮的決定,並在EventBus文檔討論:

處理程序不應該在一般情況下,拋出。如果他們這樣做,EventBus將捕獲並記錄異常。這很少是錯誤處理的正確解決方案,不應該依賴;它的目的僅僅是爲了幫助在開發過程中發現問題。

替代方案是being considered,雖然我很懷疑他們會使其進入12版

+0

你能解決這個問題嗎? – 2012-02-10 21:41:04

+1

鏈接固定,現在就試試。 – 2012-02-10 22:40:24

4

這裏是懶惰

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; 
    } 
} 
0

只是繼承番石榴EventBus,寫你自己的自定義eventbus。 提示:此類應寫入com.google.common.eventbus包中,以便可以覆蓋內部方法。

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); 
    } 
} 
相關問題