using SharedKernel.Results; namespace Web.Api.Common; public static class CustomResults { public static IResult Problem(Result result) { if (result.IsSuccess) { throw new InvalidOperationException(); } return Results.Problem( title: GetTitle(result.Error), detail: result.Error.Description, type: GetType(result.Error.Type), statusCode: GetStatusCode(result.Error.Type), extensions: GetErrors(result) ); static string GetTitle(Error error) => error.Type switch { ErrorType.Validation => error.Code, ErrorType.Problem => error.Code, ErrorType.Unauthorized => error.Code, ErrorType.NotFound => error.Code, ErrorType.Forbidden => error.Code, ErrorType.Conflict => error.Code, ErrorType.MethodNotAllowed => error.Code, _ => "Server failure" }; static string GetType(ErrorType errorType) => errorType switch { ErrorType.Validation => "https://tools.ietf.org/html/rfc7231#section-6.5.1", ErrorType.Problem => "https://tools.ietf.org/html/rfc7231#section-6.5.1", ErrorType.Unauthorized => "https://tools.ietf.org/html/rfc7235#section-3.1", ErrorType.NotFound => "https://tools.ietf.org/html/rfc7231#section-6.5.4", ErrorType.Forbidden => "https://tools.ietf.org/html/rfc7231#section-6.5.3", ErrorType.Conflict => "https://tools.ietf.org/html/rfc7231#section-6.5.8", ErrorType.MethodNotAllowed => "https://tools.ietf.org/html/rfc7231#section-6.5.5", _ => "https://tools.ietf.org/html/rfc7231#section-6.6.1" }; static int GetStatusCode(ErrorType errorType) => errorType switch { ErrorType.Validation or ErrorType.Problem => StatusCodes.Status400BadRequest, ErrorType.Unauthorized => StatusCodes.Status401Unauthorized, ErrorType.NotFound => StatusCodes.Status404NotFound, ErrorType.Forbidden => StatusCodes.Status403Forbidden, ErrorType.Conflict => StatusCodes.Status409Conflict, ErrorType.MethodNotAllowed => StatusCodes.Status405MethodNotAllowed, _ => StatusCodes.Status500InternalServerError }; static Dictionary? GetErrors(Result result) { if (result.Error is not ValidationError validationError) { return null; } return new Dictionary { { "errors", validationError.Errors } }; } } }