Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
370 views
in Technique[技术] by (71.8m points)

c# - Handling Exceptions in Reactive Extensions without stopping sequence

Why RX has the following grammar OnNext* (OnError|OnCompleted)? instead of (OnNext|OnError)* OnCompleted? This is quite clear from implementation perspective(also this has common semantics with IEnumerable and yield) but I guess differs from real life situation. In real life - producers generate mixed stream of data and exceptions (and exceptions doesn't break producer).

The question: If I understood correctly the only possible solution is to make observable return complex data structure combined from initial data and produced exceptions(Observable.Timestamp() and .TimeInterval() has similar concept) or are there any other options?


At the moment I came to the following solution: Inside observable producer I manually handle exeptions and just pass them to the following data structure which is the result of my observable

public class ValueOrException<T>
{
    private readonly Exception ex;
    private readonly T value;

    public ValueOrException(T value, Exception ex)
    {
        this.value = value;
        this.ex = ex;
    }

    public ValueOrException(T value)
    {
        this.value = value;
    }

    public T Value
    {
        get { return this.value; }
    }

    public Exception Ex
    {
        get { return this.ex; }
    }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

If the consumer is the one that knows if the Exception is expected or not, then I say that throwing exceptions is incorrect here.

You're essentially trying to convey state or logic, which exceptions are not meant to do. Exceptions are meant to bring the system (or at the very least, the current operation) to a grinding halt because something has happened which the code doesn't inherently know how to recover from.

In this case, it just so happens that an Exception is part of your business logic/state, but that doesn't mean you can throw them. You need to pass them downstream to your consumer and then have your consumer process them.

A Tuple<T, Exception> would work in a pinch here, but the lack of specificity around the type (as well as the properties) is usually messy, so I'd recommend creating a dedicated type to convey the results of your operation and is exposed through the IObservable<T>.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...