如何从ReactiveCommand赶上例外? [英] How to catch exception from ReactiveCommand?

查看:153
本文介绍了如何从ReactiveCommand赶上例外?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道如何处理由所谓的异步任务抛出的异常 ReactiveCommand< T> 但我怎么处理就是返回任务之前抛出的异常

I know how to handle exceptions thrown by async tasks called by ReactiveCommand<T> but how do I handle an exception that is thrown before the task is returned?

在下面的例子中 ThrowAndHandle 命令执行时从异步任务抛出一个异常,异常将被处理。命令 ThrowButFailToHandle 证明我不能使用 ThrownExceptions 来处理不,在任务occurr一个例外,但而之前创建任务。 ?怎么能这样的异常处理

In the following example ThrowAndHandle command will throw an exception from the async task when executed and the exception will be handled. The command ThrowButFailToHandle demonstrates that I can not use ThrownExceptions to handle an exception that does not occurr "in" the task but rather before the task is created. How can such an exception be handled?

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


推荐答案

假设你的命令直接绑定到用户界面,简单的答案是不能。

Assuming your commands are directly bound to UI, the short answer is you can't.

例外将传播到的onError的处理程序 ExecuteAsync 观察到,这是忽略按执行的实施:

The exception will be propagated to the onError handler of ExecuteAsync observable, which is ignored as per the implementation of Execute:

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

现在,如果你深深地需要捕获这个异常,你当然可以:

Now if you deeply need to catch this exception, you can certainly:


  • 包裹ReactiveCommand成一个ICommand,用不同的在错误执行行为

  • 包裹的lambda传递给 CreateAsyncCommand 返回例外在一个失败的任务结果

  • 问题/ PR上reactiveui也传播这些例外 ThrownExceptions

  • wrap the ReactiveCommand into an ICommand, with a different Execute behavior upon error
  • wrap the lambda passed to CreateAsyncCommand to return a failure task result upon exception
  • issue/PR on reactiveui to propagate these exceptions also to ThrownExceptions

这篇关于如何从ReactiveCommand赶上例外?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆