ardalis / Result

A result abstraction that can be mapped to HTTP response codes if needed.
MIT License
866 stars 107 forks source link

Map error messages when result is not found #104

Closed alemputes closed 1 year ago

alemputes commented 1 year ago

Potential solution:

public static Result<TDestination> Map<TSource, TDestination>(this Result<TSource> result, Func<TSource, TDestination> func)
        {
            switch (result.Status)
            {
                case ResultStatus.Ok: return func(result);
                case ResultStatus.NotFound:
                    return result.Errors.Any()
                        ? Result<TDestination>.NotFound(result.Errors.ToArray())
                        : Result<TDestination>.NotFound();
                case ResultStatus.Unauthorized: return Result<TDestination>.Unauthorized();
                case ResultStatus.Forbidden: return Result<TDestination>.Forbidden();
                case ResultStatus.Invalid: return Result<TDestination>.Invalid(result.ValidationErrors);
                case ResultStatus.Error: return Result<TDestination>.Error(result.Errors.ToArray());
                default:
                    throw new NotSupportedException($"Result {result.Status} conversion is not supported.");
            }
        }
KyleMcMaster commented 1 year ago

@alemputes Your suggested solution looks correct to me. Originally, the NotFound error collection and Map features were merged about the same time so this was likely just missed when things were first merged. We are planning to release a new minor version in a week or two and I will include a fix for this issue in that release.