Skip to content

Non-generic to generic Result MapFailure method #18

@paulirwin

Description

@paulirwin

There is a MapFailure method on Result<T>, but not on Result. I just encountered a situation where it makes sense to do so.

This method should be added to the non-generic Result class (note the lack of <T> compared to the generic Result<T> version):

/// <summary>
/// Maps the failure result to another type.
/// </summary>
/// <typeparam name="TOther">The type to map to.</typeparam>
/// <returns>A <see cref="Result{TOther}"/>.</returns>
/// <exception cref="InvalidOperationException">Thrown if the result type is not known.</exception>
public Result<TOther> MapFailure<TOther>() =>
    this switch
    {
        SuccessResult => throw new InvalidOperationException("Cannot map failure on success result"),
        ValidationFailedResult validationFailed => Result<TOther>.ValidationFailed(validationFailed.Errors),
        UnauthorizedResult unauthorized => Result<TOther>.Unauthorized(unauthorized.Message),
        PreconditionFailedResult preconditionFailed => Result<TOther>.PreconditionFailed(preconditionFailed.Reason, preconditionFailed.Message),
        _ => throw new InvalidOperationException("Unknown result type")

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementNew feature or request

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions