3

这是一个介绍反应式框架的简单程序。但我想尝试错误处理程序,将程序修改为:

var cookiePieces = Observable.Range(1, 10);
cookiePieces.Subscribe(x =>
   {
      Console.WriteLine("{0}! {0} pieces of cookie!", x);
      throw new Exception();  // newly added by myself
   },
      ex => Console.WriteLine("the exception message..."),
      () => Console.WriteLine("Ah! Ah! Ah! Ah!"));
Console.ReadLine();

在此示例中,使用了以下重载。

public static IDisposable Subscribe<TSource>(
     this IObservable<TSource> source, 
     Action<TSource> onNext, 
     Action<Exception> onError, 
     Action onCompleted);

我希望我会看到打印的异常消息,但是控制台应用程序崩溃了。是什么原因?

4

3 回答 3

5

异常处理程序用于在 observable 本身中创建的异常,而不是由观察者创建的。

引发异常处理程序的一种简单方法是这样的:

using System;
using System.Linq;

class Test
{
    static void Main(string[] args)
    {
        var xs = Observable.Range(1, 10)
                           .Select(x => 10 / (5 - x));

        xs.Subscribe(x => Console.WriteLine("Received {0}", x),
                     ex => Console.WriteLine("Bang! {0}", ex),
                     () => Console.WriteLine("Done"));

        Console.WriteLine("App ending normally");
    }
}

输出:

Received 2
Received 3
Received 5
Received 10
Bang! System.DivideByZeroException: Attempted to divide by zero.
   at Test.<Main>b__0(Int32 x)
   at System.Linq.Observable.<>c__DisplayClass35a`2.<>c__DisplayClass35c.<Select
>b__359(TSource x)
App ending normally
于 2010-07-13T09:54:00.297 回答
3

在 Rx 库中,任何传递给操作 IObservable(Select、Where、GroupBy 等)的操作符的用户代码都将被捕获并发送到订阅 observable 的观察者的 OnError 处理程序。处理这些的原因是它们是计算的一部分。

观察者代码中发生的异常必须由用户处理。由于它们处于计算的末尾,Rx 不清楚如何处理这些。

于 2010-07-13T17:12:54.597 回答
0

它是否真的崩溃或跳入 Visual Studio 并向您显示发生了异常?如果第二个为真,您应该查看菜单栏中的 Debug - Exception 并取消选择右侧的所有内容。

于 2010-07-13T10:04:28.847 回答