I am trying to handle some tasks asynchronously using Rx, for example.
var list = Enumerable.Range(0, 100) .ToObservable() .SelectMany(x => Observable.Start(() => { Console.WriteLine("Processing {0} ...", x); Thread.Sleep(100 * x % 3); if (x > 90) { Console.WriteLine("Procesing exception {0} > 90", x); throw new Exception("Value too large"); } Console.WriteLine("Processing {0} completed.", x); return x; })) .Subscribe( x => { Console.WriteLine("Next [{0}]", x); }, e => { Console.WriteLine("Exception:"); Console.WriteLine(e.Message); }, () => { Console.WriteLine("Complete"); } );
The problem with this code is that the exception is not passed to the subscriber. So, after many attempts, I gave up and decided to ask this simple question:
How do you handle exceptions that arise from asynchronous methods in a SelectMany
?
To make this clear, the final implementation is a call to a synchronous function that may or may not throw an exception. The goal is to transfer it to the subscriber so that it can be further processed (in a specific case, a message will be shown to the user).
Edit
I transferred my findings to an answer so that I could mark this question as he answered. Personally, I do not agree with the answer to myself ... but sometimes there is no other way, so I'm sorry.
source share