如何从ReactiveCommand赶上例外?

编程入门 行业动态 更新时间:2024-10-18 01:29:29
本文介绍了如何从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赶上例外?

本文发布于:2023-11-07 10:49:06,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1566250.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:ReactiveCommand

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!