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

Alternate proposal for ASP.NET Core conversion #110

Draft
wants to merge 3 commits into
base: asp-net-core-nuget
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
109 changes: 109 additions & 0 deletions src/ErrorOr.AspNetCore/DefaultConversion/ErrorDefaults.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,109 @@
using Microsoft.AspNetCore.Http;

namespace ErrorOr;

public static class ErrorDefaults
{
public static ProblemDetailInfo Validation { get; } = new (
ErrorType.Validation,
StatusCodes.Status400BadRequest,
"https://tools.ietf.org/html/rfc9110#section-15.5.1",
"Bad Request");

public static ProblemDetailInfo Unauthorized { get; } = new (
ErrorType.Unauthorized,
StatusCodes.Status401Unauthorized,
"https://tools.ietf.org/html/rfc9110#section-15.5.2",
"Unauthorized");

public static ProblemDetailInfo Forbidden { get; } = new (
ErrorType.Forbidden,
StatusCodes.Status403Forbidden,
"https://tools.ietf.org/html/rfc9110#section-15.5.4",
"Forbidden");

public static ProblemDetailInfo NotFound { get; } = new (
ErrorType.NotFound,
StatusCodes.Status404NotFound,
"https://tools.ietf.org/html/rfc9110#section-15.5.5",
"Not Found");

public static ProblemDetailInfo Conflict { get; } = new (
ErrorType.Conflict,
StatusCodes.Status409Conflict,
"https://tools.ietf.org/html/rfc9110#section-15.5.10",
"Conflict");

public static ProblemDetailInfo Gone { get; } = new (
ErrorType.Gone,
StatusCodes.Status410Gone,
"https://tools.ietf.org/html/rfc9110#section-15.5.11",
"Gone");

public static ProblemDetailInfo PreconditionFailed { get; } = new (
ErrorType.PreconditionFailed,
StatusCodes.Status412PreconditionFailed,
"https://tools.ietf.org/html/rfc9110#section-15.5.13",
"Precondition Failed");

public static ProblemDetailInfo UnsupportedMediaType { get; } = new (
ErrorType.UnsupportedMediaType,
StatusCodes.Status415UnsupportedMediaType,
"https://tools.ietf.org/html/rfc9110#section-15.5.16",
"Unsupported Media Type");

public static ProblemDetailInfo UnprocessableEntity { get; } = new (
ErrorType.UnprocessableEntity,
StatusCodes.Status422UnprocessableEntity,
"https://tools.ietf.org/html/rfc4918#section-11.2",
"Unprocessable Entity");

public static ProblemDetailInfo UnavailableForLegalReasons { get; } = new (
ErrorType.UnavailableForLegalReasons,
StatusCodes.Status451UnavailableForLegalReasons,
"https://tools.ietf.org/html/rfc7725#section-3",
"Unavailable for Legal Reasons");

public static ProblemDetailInfo Failure { get; } = new (
ErrorType.Failure,
StatusCodes.Status500InternalServerError,
"https://tools.ietf.org/html/rfc9110#section-15.6.1",
"An error occurred while processing your request.");

public static ProblemDetailInfo BadGateway { get; } = new (
ErrorType.BadGateway,
StatusCodes.Status502BadGateway,
"https://tools.ietf.org/html/rfc9110#section-15.6.3",
"Bad Gateway");

public static ProblemDetailInfo ServiceUnavailable { get; } = new (
ErrorType.ServiceUnavailable,
StatusCodes.Status503ServiceUnavailable,
"https://tools.ietf.org/html/rfc9110#section-15.6.4",
"Service Unavailable");

public static ProblemDetailInfo GatewayTimeout { get; } = new (
ErrorType.GatewayTimeout,
StatusCodes.Status504GatewayTimeout,
"https://tools.ietf.org/html/rfc9110#section-15.6.5",
"Gateway Timeout");

public static Dictionary<ErrorType, ProblemDetailInfo> DefaultMappings { get; } =
new[]
{
Validation,
Unauthorized,
Forbidden,
NotFound,
Conflict,
Gone,
PreconditionFailed,
UnsupportedMediaType,
UnprocessableEntity,
Failure,
BadGateway,
ServiceUnavailable,
GatewayTimeout,
}
.ToDictionary(i => i.ErrorType);
}
29 changes: 29 additions & 0 deletions src/ErrorOr.AspNetCore/DefaultConversion/ErrorExtensions.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
namespace ErrorOr;

public static class ErrorExtensions
{
public static ErrorType GetLeadingErrorType(this List<Error> errors, bool firstTypeIsLeadingType = false)
{
ArgumentNullException.ThrowIfNull(errors);
if (errors.Count == 0)
{
throw new ArgumentException("errors must have at least one item", nameof(errors));
}

var firstType = errors[0].Type;
if (firstTypeIsLeadingType || errors.Count == 1)
{
return firstType;
}

for (var i = 1; i < errors.Count; i++)
{
if (firstType != errors[i].Type)
{
return ErrorType.Failure;
}
}

return firstType;
}
}
28 changes: 28 additions & 0 deletions src/ErrorOr.AspNetCore/DefaultConversion/ErrorProblemDetails.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
using System.Text.Json.Serialization;
using Microsoft.AspNetCore.Mvc;

namespace ErrorOr;

public class ErrorProblemDetails : ProblemDetails
{
/// <summary>
/// Initializes a new instance of <see cref="ErrorProblemDetails" />.
/// </summary>
/// <param name="errors">The dictionary that contains the errors for the problem details.</param>
public ErrorProblemDetails(List<Error> errors)
{
ArgumentNullException.ThrowIfNull(errors);
if (errors.Count is 0)
{
throw new ArgumentException("The errors list must contain at least one error.", nameof(errors));
}

Errors = errors;
}

/// <summary>
/// Gets the errors associated with this instance of <see cref="ErrorProblemDetails" />.
/// </summary>
[JsonPropertyName("errors")]
public List<Error> Errors { get; }
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
using Microsoft.AspNetCore.Mvc.ModelBinding;

namespace ErrorOr;

public static class ModelStateDictionaryExtensions
{
public static ModelStateDictionary AddErrors(
this ModelStateDictionary modelStateDictionary,
List<Error> errors)
{
foreach (var error in errors)
{
modelStateDictionary.AddModelError(error.Code, error.Description);
}

return modelStateDictionary;
}
}
9 changes: 9 additions & 0 deletions src/ErrorOr.AspNetCore/DefaultConversion/ProblemDetailInfo.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
namespace ErrorOr;

public readonly record struct ProblemDetailInfo(
ErrorType ErrorType,
int StatusCode,
string Type,
string Title,
string? Detail = null
);
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
namespace ErrorOr;

public readonly record struct ProblemDetailsPrototype(
List<Error> Errors,
ErrorType LeadingErrorType,
int? StatusCode = null,
string? Title = null,
string? Detail = null,
string? Type = null,
string? Instance = null
)
{
public static ProblemDetailsPrototype CreateDefaultFromErrors(
List<Error> errors,
Dictionary<ErrorType, ProblemDetailInfo>? errorDefaults = null,
bool useFirstErrorAsLeadingType = false)
{
errorDefaults ??= ErrorDefaults.DefaultMappings;
var leadingErrorType = errors.GetLeadingErrorType(useFirstErrorAsLeadingType);
if (!errorDefaults.TryGetValue(leadingErrorType, out var problemDetailInfo))
{
problemDetailInfo = ErrorDefaults.Failure;
}

return new ProblemDetailsPrototype(
errors,
problemDetailInfo.ErrorType,
problemDetailInfo.StatusCode,
problemDetailInfo.Title,
Type: problemDetailInfo.Type);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,97 @@
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Infrastructure;
using Microsoft.AspNetCore.Mvc.ModelBinding;

namespace ErrorOr;

public static class ProblemDetailsPrototypeExtensions
{
public static ProblemDetails ConvertToProblemDetails(
this ProblemDetailsPrototype prototype,
bool includeErrorMetadata = false) =>
prototype.LeadingErrorType == ErrorType.Validation ?
prototype.ConvertToValidationProblemDetails(includeErrorMetadata) :
prototype.ToErrorProblemDetails();

public static ProblemDetails ConvertToProblemDetails(
this ProblemDetailsPrototype prototype,
HttpContext httpContext,
ProblemDetailsFactory factory,
bool includeErrorMetadata = false,
ModelStateDictionary? modelStateDictionary = null)
{
ProblemDetails problemDetails;
if (prototype.LeadingErrorType == ErrorType.Validation)
{
modelStateDictionary ??= new ModelStateDictionary();
modelStateDictionary.AddErrors(prototype.Errors);
problemDetails = factory.CreateValidationProblemDetails(
httpContext,
modelStateDictionary,
prototype.StatusCode,
prototype.Title,
prototype.Type,
prototype.Detail,
prototype.Instance);
}
else
{
problemDetails = factory.CreateProblemDetails(
httpContext,
prototype.StatusCode,
prototype.Title,
prototype.Type,
prototype.Detail,
prototype.Instance);
}

if (includeErrorMetadata)
{
problemDetails.AddExtensions(prototype.Errors);
}

return problemDetails;
}

private static ErrorProblemDetails ToErrorProblemDetails(this ProblemDetailsPrototype prototype)
{
return new ErrorProblemDetails(prototype.Errors)
{
Status = prototype.StatusCode,
Type = prototype.Type,
Title = prototype.Title,
Instance = prototype.Instance,
Detail = prototype.Detail ?? "See the errors property for more information.",
};
}

private static ValidationProblemDetails ConvertToValidationProblemDetails(this ProblemDetailsPrototype prototype, bool includeErrorMetadata)
{
var problemDetails = new ValidationProblemDetails
{
Type = prototype.Type,
Status = prototype.StatusCode,
Detail = prototype.Detail,
Instance = prototype.Instance,
Errors = prototype
.Errors
.GroupBy(error => error.Code)
.ToDictionary(
group => group.Key,
group => group.Select(error => error.Description).ToArray()),
};

if (prototype.Title is not null)
{
problemDetails.Title = prototype.Title;
}

if (includeErrorMetadata)
{
problemDetails.AddExtensions(prototype.Errors);
}

return problemDetails;
}
}
19 changes: 9 additions & 10 deletions src/ErrorOr.AspNetCore/DependencyInjection/ErrorOrOptions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,15 +5,14 @@ namespace ErrorOr;

public class ErrorOrOptions
{
public static readonly ErrorOrOptions Instance = new();
public static ErrorOrOptions Instance { get; } = new();

public bool IncludeMetadataInProblemDetails { get; set; } = false;
public List<Func<List<Error>, IResult?>> ErrorListToResultMapper { get; set; } = [];
public List<Func<Error, IResult?>> ErrorToResultMapper { get; set; } = [];
public List<Func<List<Error>, IActionResult?>> ErrorListToActionResultMapper { get; set; } = [];
public List<Func<Error, IActionResult?>> ErrorToActionResultMapper { get; set; } = [];
public List<Func<List<Error>, ProblemDetails?>> ErrorListToProblemDetailsMapper { get; set; } = [];
public List<Func<Error, ProblemDetails?>> ErrorToProblemDetailsMapper { get; set; } = [];
public List<Func<Error, int?>> ErrorToStatusCodeMapper { get; set; } = [];
public List<Func<Error, string?>> ErrorToTitleMapper { get; set; } = [];
public bool IncludeMetadata { get; set; }
public bool UseProblemDetailsFactoryInMvc { get; set; }
public bool UseFirstErrorAsLeadingType { get; set; }
public Func<List<Error>, IActionResult>? CustomToErrorActionResult { get; set; }
public Func<List<Error>, IResult>? CustomToErrorResult { get; set; }
public Func<List<Error>, ProblemDetailsPrototype>? CustomCreatePrototype { get; set; }
public Dictionary<ErrorType, ProblemDetailInfo> ErrorDefaults { get; set; } =
new (ErrorOr.ErrorDefaults.DefaultMappings);
}
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,7 @@ public static class ServiceCollectionExtensions
public static IServiceCollection AddErrorOr(this IServiceCollection services, Action<ErrorOrOptions> options)
{
options.Invoke(ErrorOrOptions.Instance);

services.AddSingleton(ErrorOrOptions.Instance);

return services;
}
}
Loading