2015-10-07 76 views
2

我知道如何處理由ReactiveCommand<T>調用的異步任務拋出的異常,但是如何處理返回任務之前拋出的異常呢?如何從ReactiveCommand中捕獲異常?

在以下示例中,ThrowAndHandle命令將在異步任務執行時拋出異常並處理異常。命令ThrowButFailToHandle表明我不能使用ThrownExceptions來處理任務中未發生的異常,而是在創建任務之前處理異常。如何處理這樣的例外?

public class ViewModel 
{ 
    public IReactiveCommand ThrowAndHandle { get; private set; } 
    public IReactiveCommand ThrowButFailToHandle { get; private set; } 

    public ViewModel() 
    { 
     ThrowAndHandle = ReactiveCommand.CreateAsyncTask(_ => ThrowFromTask()); 
     ThrowAndHandle.ThrownExceptions.Subscribe(HandleException); 

     ThrowButFailToHandle = ReactiveCommand.CreateAsyncTask(_ => ThrowBeforeTaskIsReturned()); 
     ThrowButFailToHandle.ThrownExceptions.Subscribe(ThisMethodWillNotBeCalled); 
    } 

    private Task ThrowFromTask() 
    { 
     return Task.Run(() => 
     { 
      throw new Exception("This exception will appear in IReactiveCommand.ThrownExceptions"); 
     }); 
    } 

    private Task ThrowBeforeTaskIsReturned() 
    { 
     throw new Exception("How can I handle this exception?"); 
    } 

    private void HandleException(Exception ex) 
    { 
     // This method is called when ThrownFromTask() is called 
    } 

    private void ThisMethodWillNotBeCalled(Exception ex) 
    { 
    } 
} 

回答

1

假設你的命令直接綁定到UI,簡短的答案是你不能。

的異常將被傳播到ExecuteAsync的onError的處理程序觀察到的,這是忽略了爲每Execute實現:

public void Execute(object parameter) 
    { 
     ExecuteAsync(parameter).Catch(Observable.Empty<T>()).Subscribe(); 
    } 

現在,如果你深深地需要捕捉這個異常,可以肯定:

  • 包裹ReactiveCommand成一個ICommand,具有在錯誤
  • 不同Execute行爲包裹拉姆達傳遞給CreateAsyncCommand在異常時返回失敗任務結果
  • issue/PR on_realui將這些異常傳播到ThrownExceptions