1

i have this code(sample source code from sample code)

i change a little this code for get exception with onError like :

  IObservable<int> source = Observable.Range(1, 10);
        IDisposable subscription = source.Subscribe<int>(
            onNext =>
            {
                int zero = 0;                //added this code
                var div = onNext / zero;     //and this code for get execption
            },
             onError =>
            { 
                Console.WriteLine("OnError: {0}", onError.Message); // This code never runs
            });
        subscription.Dispose();

how to set exception to onError?

jack wilsher
  • 67
  • 1
  • 10

1 Answers1

3

The onError here is supposed to catch exception errors emitted by source, not by your callback onNext.

I would say the try ... catch inside onNext is the usual way to go here, though it's understandable that you want to reuse your error handling in onError.

If you want to force this pattern here, what you could do is to pipe your observable to another that executes the code you want to catch, with a Do for instance, and subscribe to the result observable.

something like :

IObservable<int> source = Observable.Range(1, 10);

IDisposable subscription = source.Do(_ =>
    {
        // Here goes the code you had in your 'onNext' originally
        throw new Exception("Throw exception manually for test purposes.");
    })
    .Subscribe(
        _ => { /* nothing to do */ },
        error =>
        { 
            Console.WriteLine("OnError: {0}", error.Message);
        }
    );

Related Q&A : How to handle exceptions in OnNext when using ObserveOn? (I don't think this is an exact duplicate, but a part overlaps with this question, IMO)

Pac0
  • 21,465
  • 8
  • 65
  • 74