Skip to content

Latest commit

 

History

History
93 lines (71 loc) · 2.37 KB

File metadata and controls

93 lines (71 loc) · 2.37 KB

Sstv.DomainExceptions.Extensions.ProblemDetails

<- root readme

<- changelog

This library brings to Sstv.DomainExceptions additional capabilities to create response in ProblemDetails format

Install

You can install using Nuget Package Manager:

Install-Package Sstv.DomainExceptions.Extensions.ProblemDetails

via the .NET CLI:

dotnet add package Sstv.DomainExceptions.Extensions.ProblemDetails

or you can add package reference manually:

<PackageReference Include="Sstv.DomainExceptions.Extensions.ProblemDetails" />

How to use?

Register to Dependency injection:

Call UseDomainExceptionHandler extension method on DomainExceptionBuilder:

services.AddDomainExceptions(builder =>
{
    builder.UseDomainExceptionHandler();

    // other config
});

Add AspNetCore built-in ProblemDetails

services.AddProblemDetails(x =>
{
    x.CustomizeProblemDetails = context =>
    {
        // when domain exception occurs, we can grab error code and map HTTP status code for him
        if (context.Exception is DomainException de)
        {
            context.ProblemDetails.Status = context.HttpContext.Response.StatusCode = ErrorCodeMapping.MapToStatusCode(de.ErrorCode);
        }
        else
        {
            // for other exceptions we can add default error code for consistent behavior
            context.ProblemDetails = new ErrorCodeProblemDetails(ErrorCodes.Default.GetDescription())
            {
                Status = context.HttpContext.Response.StatusCode = StatusCodes.Status500InternalServerError
            };
        }
    };
})

Please, look at here for additional examples.

Add exception handler middlware

app.UseExceptionHandler();

after that, we can throw exception and see results

throw ErrorCodes.NotEnoughMoney.ToException()
                .WithDetailedMessage("You want 500, but your account balance is 300.");
{
    "type": "https://help.myproject.ru/error-codes/not-enough-money",
    "title": "You have not enough money",
    "detail": "You want 500, but your account balance is 300.",
    "status": 200,
    "code": "SSTV10001",
    "criticalityLevel": "Low",
    "errorId": "ad3f064c-1254-41dd-82e4-891507937cf6"
}