Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add exception based Filter #69

Open
wldevries opened this issue Jul 18, 2019 · 1 comment
Open

Add exception based Filter #69

wldevries opened this issue Jul 18, 2019 · 1 comment
Milestone

Comments

@wldevries
Copy link

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);

@nlkl
Copy link
Owner

nlkl commented Jul 18, 2019

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants