【发布时间】:2011-11-04 19:41:08
【问题描述】:
我对 Rx.NET 有点陌生。是否有可能捕获任何订阅者可能抛出的异常?采取以下...
handler.FooStream.Subscribe(
_ => throw new Exception("Bar"),
_ => { });
目前,我正在以每个订阅为基础使用以下实例。其中的实现只是使用 ManualResetEvent 来唤醒等待线程。
public interface IExceptionCatcher
{
Action<T> Exec<T>(Action<T> action);
}
并像这样使用它......
handler.FooStream.Subscribe(
_exceptionCatcher.Exec<Foo>(_ => throw new Exception("Bar")), //It's disappointing that this generic type can't be inferred
_ => { });
我觉得一定有更好的方法。 Rx.NET 中的所有错误处理功能都是专门用于处理可观察到的错误吗?
编辑:根据请求,我的实现是https://gist.github.com/1409829(接口和实现在产品代码中分成不同的程序集)。欢迎反馈。这可能看起来很傻,但我正在使用城堡温莎来管理许多不同的 Rx 订阅者。这个异常捕获器像这样在容器中注册
windsorContainer.Register(Component.For<IExceptionCatcher>().Instance(catcher));
然后它将像这样使用,其中observable 是 IObservable 的实例:
var exceptionCatcher =
new ExceptionCatcher(e =>
{
Logger.FatalException(
"Exception caught, shutting down.", e);
// Deal with unmanaged resources here
}, false);
/*
* Normally the code below exists in some class managed by an IoC container.
* 'catcher' would be provided by the container.
*/
observable /* do some filtering, selecting, grouping etc */
.SubscribeWithExceptionCatching(processItems, catcher);
【问题讨论】:
标签: c# exception-handling asynchronous system.reactive subscription