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)
{
}
}