Skip to content

Add exception based Filter #69

@wldevries

Description

@wldevries

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions