Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.NET ReactiveExtension observer isn't catching errors in OnError

When using ReactiveExtension Observer exceptions are not being caught by the onError action. Using the example code below instead of the exception being caught "An unhandled exception of type 'System.ApplicationException' occurred in System.Reactive.Core.dll" and the application terminates. The exception seems to bypass every try/catch in the calling stack.

var source = Observable.Interval(TimeSpan.FromSeconds(seconds));
var observer = Observer.Create<long>(
    l =>
    { 
       //do something
       throw new ApplicationException("test exception");
    },
    ex => Console.WriteLine(ex));
var subscription = source.Subscribe(observer);

Am I missing how exceptions are supposed to handled by observables?

If I put a try catch in the onNext action then exception is caught and I can log it.

var source = Observable.Interval(TimeSpan.FromSeconds(seconds));
var observer = Observer.Create<long>(
    l =>
    { 
       try
       {
         //do something
         throw new ApplicationException("test exception");
       }
       catch(Exception ex)
       {
          //exception can be caught here and logged
          Console.WriteLine(ex);
       }
    },
    ex => Console.WriteLine(ex));
var subscription = source.Subscribe(observer);

What do I need to do to have the exception caught by the onError action?

like image 634
Chris Lunt Avatar asked Feb 18 '15 22:02

Chris Lunt


Video Answer


1 Answers

Exceptions are only caught if they are raised in the observable. If they are raised in the observer then you have to catch them yourself.

This makes sense for a number of reasons:

  1. If you had several observers attached to a hot observable then you don't want the stream to be terminated because one of the observers did something wrong.
  2. You don't want the other observers knowing about the workings of the other observers
  3. If the exception is thrown in one observer after another has successfully processed a value but before the next one observes it you could end up in an inconsistent state.
like image 98
Enigmativity Avatar answered Oct 29 '22 17:10

Enigmativity