Optional icon indicating copy to clipboard operation
Optional copied to clipboard

Add exception based Filter

Open wldevries opened this issue 5 years ago • 1 comments

I need to handle request results that may contain errors and I want to filter away the error into an exception. An example of what I'm trying to accomplish is the following code. When the status of the result is Error I want to filter it away into a RequestError with the given message, but the API only allows constant values for the exceptional value.

return result.Map(json => JsonConvert.DeserializeObject<StatusEnvelope<RouteData>>(json))
    .Filter(e => e.Status == "Error", e => new RequestError(e.Error))
    .Map(re => re.Value);

The best solution I could come up with is rather verbose:

return result.Map(json => JsonConvert.DeserializeObject<StatusEnvelope<RouteData>>(json))
    .Match(
    r => 
    {
        return r.Status == "Error"
            ? Option.None<RouteData>().WithException<Error>(new RequestError(r.Error))
            : r.Value.Some<RouteData, Error>();
    },
    e => Option.None<RouteData>().WithException(e));

Suggested addition to the API: public Option<T, TException> Filter(Func<T, bool> predicate, Func<T, TException> exception);

wldevries avatar Jul 18 '19 12:07 wldevries

Hi!

Good observation - I agree this should be added to the API.

There is a Filter which takes a func, Func<TException>, but that doesn't let you use the value you filtered on. The same is true for e.g. FlatMap.

Feel free to add this in a PR if you have time (on the develop branch) - otherwise I will add it when I get around to it.

Regarding what you can do here and now, this is slightly less verbose, but still not nearly as readable as one could desire:

return result
    .Map(json => JsonConvert.DeserializeObject<StatusEnvelope<RouteData>>(json))
    .FlatMap(e => 
        e.Status == "Error"
            ? Option.Some<RouteData, Error>(e.Value)
            : Option.None<RouteData, Error>(new RequestError(e.Error)
    );

/ Nils

nlkl avatar Jul 18 '19 17:07 nlkl