Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to handle exception on a behaviour subject

I have a behavior subject

var source = new BehaviorSubject<int>(0);

I then process that source with something like

var withErrors = source
            .Select(v =>
            {
                if (v == 2)
                {
                    throw new Exception("Ouch ");
                }
                return v;
            })

I want to subscribe to withErrors in such a way that I can skip the errors. An attempt with catch like this.

public IObservabe<int> SkipError(IObservable<T> source){

    return source
       .Catch(e=>SkipErrors(source.Skip(1));
}

and then call it thus

var withoutErrors = SkipError(withErrors);

the Skip is an attempt to avoid repeating the last error on the behaviour subject but alas it doesn't work that way. Skip doesn't skip over errors but only over valid data so the error from the current state in the behavior subject keeps getting through.

Is there a clever way of writing Skip that will also skip over errors. Something tells me this is not possible but hopefully I'm wrong

like image 824
bradgonesurfing Avatar asked Nov 03 '22 17:11

bradgonesurfing


1 Answers

As the premise of the question is wrong I present a better way to do this using the Exceptional<T> monad. For example

IObservable<int> source = ....;
IObservable<Exceptional<string>> withErrors =
    source.Select(i=>Exceptional.Execute(()=>{
        if(v==2){
            throw new Exception("Ouch");
        }
        return v.ToString();
    });


IObservable<Exception> errors = 
    withErrors.Where(v=>v.HasException).select(v=>v.Exception);

IObservable<string> values =
    withErrors.Where(v=>!v.HasException).select(v=>v.Value);

and just for fun you can do

Exceptional<string> r = 
         from x in Exceptional.Execute(() => "xxx")
         from y in Exceptional.Execute(() => "zzz")
         select x + y;

which will generation an Exceptional holding the value "xxxzzz". If any of the steps does throw an exception then it will short circuit and hold only the Exception.

My implementation based off another SO answer is https://gist.github.com/bradphelan/6154972

like image 56
bradgonesurfing Avatar answered Nov 14 '22 10:11

bradgonesurfing