简体   繁体   English

观察者不能捕获动态扩展方法中抛出的异常

[英]Observer CANNOT catch exception thrown in dynamic extension method

I created an extension to another class.我创建了另一个 class 的扩展。 I invoked the extension method, which throws exception.我调用了引发异常的扩展方法。 Unfortunately, my observer CANNOT catch that exception.不幸的是,我的观察者无法捕捉到该异常。

Anybody knows why?有人知道为什么吗?

public static class MyExtensions {
    public static async void myextfunc(this SomeClass some, dynamic data) {
        throw new Exception("Atrápame si puedes.");
    } // fin myextfunc()
} // fin class



SomeClass some = new SomeClass();
IObserver<dynamic> obsv = Observer.Create<dynamic>(async (d) => {
    some.myextfunc((object)d); // NO PUEDO atrapar la exceptión
}, (exception0) => {
    Console.WriteLine(e1.Message);
});
try { obsv.OnNext(123); } catch { /* no funciona */ }

Actually, this behavior doesn't depend on using extension method.实际上,这种行为不依赖于使用扩展方法。 It depends on using async function when a method expects synchronous delegate ( Observer.Create takes only Action< T > as an input for onNext).当方法需要同步委托时,它依赖于使用异步function( Observer.Create仅将 Action< T > 作为 onNext 的输入)。

First of all, you should never use async void because there is no way for caller to await it correctly (meaning that there will be no exception handling by try / catch for example, more details here ).首先,您永远不应该使用async void因为调用者无法正确等待它(这意味着例如try / catch将不会处理异常,更多细节在这里)。 But even if we try to change your code (adding Task instead of void return to your extension method and awaiting it in Observer's onNext) it won't work.但即使我们尝试更改您的代码(将 Task 而不是 void return 添加到您的扩展方法并在 Observer 的 onNext 中等待它)它也不会起作用。

It happens exactly because of Observer.Create expecting Action< T >, not Func< Task >.它的发生正是因为Observer.Create期望 Action<T>,而不是 Func<Task>。

It's hard to understand what exactly you wanted to achieve, so I played with your code assuming you want to catch exception thrown from your async call.很难理解您到底想要实现什么,所以我使用您的代码假设您想要捕获异步调用引发的异常。 That's what I've got:这就是我所拥有的:

async static Task Main(string[] args)
{
    SomeClass some = new SomeClass();

    var subscription = Observable.Interval(TimeSpan.FromSeconds(1))
        .SelectMany(number => Observable.FromAsync(async () => await some.myextfunc(number)))
        .Subscribe(_ => Console.WriteLine("onNext"),
            ex => Console.WriteLine(ex.Message));

    await Task.Delay(TimeSpan.FromSeconds(10));
}

You can find out more from this discussion on GitHub and by searching SO questions on async / await with RX.您可以从有关 GitHub 的讨论中找到更多信息,也可以通过搜索关于 async / await with RX 的 SO 问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM