DotNetBrightener.AspNet.Extensions.SelfDocumentedProblemResult 2024.0.14.6-rc-242771401

This is a prerelease version of DotNetBrightener.AspNet.Extensions.SelfDocumentedProblemResult.
There is a newer prerelease version of this package available.
See the version list below for details.
dotnet add package DotNetBrightener.AspNet.Extensions.SelfDocumentedProblemResult --version 2024.0.14.6-rc-242771401                
NuGet\Install-Package DotNetBrightener.AspNet.Extensions.SelfDocumentedProblemResult -Version 2024.0.14.6-rc-242771401                
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="DotNetBrightener.AspNet.Extensions.SelfDocumentedProblemResult" Version="2024.0.14.6-rc-242771401" />                
For projects that support PackageReference, copy this XML node into the project file to reference the package.
paket add DotNetBrightener.AspNet.Extensions.SelfDocumentedProblemResult --version 2024.0.14.6-rc-242771401                
#r "nuget: DotNetBrightener.AspNet.Extensions.SelfDocumentedProblemResult, 2024.0.14.6-rc-242771401"                
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
// Install DotNetBrightener.AspNet.Extensions.SelfDocumentedProblemResult as a Cake Addin
#addin nuget:?package=DotNetBrightener.AspNet.Extensions.SelfDocumentedProblemResult&version=2024.0.14.6-rc-242771401&prerelease

// Install DotNetBrightener.AspNet.Extensions.SelfDocumentedProblemResult as a Cake Tool
#tool nuget:?package=DotNetBrightener.AspNet.Extensions.SelfDocumentedProblemResult&version=2024.0.14.6-rc-242771401&prerelease                

ASP.NET Core WebApp Self-Documented Problem Result Extension

© 2024 DotNet Brightener

NuGet Version

Introduction

Have you ever wanted to have a consistent way of returning errors from your ASP.NET Core Web application? This package provides an abstraction for responding errors from your application to the client, base on the RFC 9457 specification.

When the application encounter an error, it should return a ProblemDetails object that contains information about the error.

This package

  • Added a global exception handler to catch unhandled exceptions and return a ProblemDetails object. An ILogger is also added to log the exception automatically for the unhandled exceptions.

  • Provides a based IProblembResult interface and its extension methods ToProblemDetails() or ToProblemResult(), to create consistent error responses. The error response format is based on the RFC 9457 specification.

When your application needs to response the error, you can either throw an exception derived from BaseProblemDetailsError class or simply create a class that implements IProblemResult interface. The error object will be converted to ProblemDetails object and returned to the client. Check Usage section for more information.

Installation

You can install the package from NuGet:


dotnet add package DotNetBrightener.AspNet.Extensions.SelfDocumentedProblemResult

Usage

1. Enable the global exception handler

Add the following code to your Startup.cs (if you use Startup.cs) or Program.cs (by default) file:


// this can be omitted if your application already added IHttpContextAccessor
builder.Services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();

// The default way of handling unhandled exceptions
builder.Services.AddExceptionHandler<UnhandledExceptionResponseHandler>();

// Adds services required for creation of <see cref="ProblemDetails"/> for failed requests.
builder.Services.AddProblemDetails();


// Add the following to your Configure method, 
// or after 
// var app = builder.Build(); if you use Program.cs
app.UseExceptionHandler();

After the configuration above, if your application throws an exception, the response will be a ProblemDetails object.

2. Create a consistent error response

2.1. Using Exception approach

Traditionally we used to throw exceptions when there are errors. You can create an exception class that inherits BaseProblemDetailsError class. The <summary> and <remarks> XML comments will be used to generate the ProblemDetails object.


/// <summary>
///     The error represents the requested object of type `User` could not be found
/// </summary>
/// <remarks>
///     The error is thrown because the requested resource of type `User` could not be found
/// </remarks>
public class UserNotFoundException : BaseProblemDetailsError
{
    public UserNotFoundException()
        : base("User Not Found", HttpStatusCode.BadRequest)
    {
    }

    public UserNotFoundException(long userId)
        : this()
    {
        Data.Add("userId", userId);
    }
}

Somewhere in your application, where an error is expected, you can throw the exception as followed:

// UserService.cs

    public User GetUser(long userId)
    {
        var user = _userRepository.GetUser(userId);

        if (user == null)
        {
            throw new UserNotFoundException(userId);
        }

        return user;
    }

Without having to handle the exception, the error will be caught by the global exception handler and return a ProblemDetails object.

// UserController.cs

    [HttpGet("{userId}")]
    public IActionResult GetUserDetail(long userId)
    {
        var user = _userService.GetUser(userId);

        // Without handling the exception, the error will be caught by the global exception handler

        return Ok(user);
    }

2.2. Using ProblemResult approach

Create a class that inherits BaseProblemDetailsError. The <summary> and <remarks> XML comments will be used to generate the ProblemDetails object.


using AspNet.Extensions.SelfDocumentedProblemResult.ErrorResults;

/// <summary>
///     The error represents the requested object of type `User` could not be found
/// </summary>
/// <remarks>
///     The error is thrown because the requested resource of type `User` could not be found
/// </remarks>
public class UserNotFoundError : BaseProblemDetailsError
{
    public UserNotFoundError()
        : base(HttpStatusCode.NotFound)
    {

    }

    public UserNotFoundError(long userId)
        : this()
    {
        Data.Add("userId", userId);
    }
}

// UserService.cs

    public User GetUser(long userId)
    {
        var user = _userRepository.GetUser(userId);

        return user;
    }

Somewhere in your controller, where an error is expected, you can return the error like this:

// UserController.cs
    [HttpGet("{userId}")]
    public IActionResult GetUserDetail(long userId)
    {
        var user = _userService.GetUser(userId);
        if (user == null)
        {
            // Explicitly return the error
            var error = new UserNotFoundError(userId);

            return error.ToProblemResult();
        }

        // Omited for brevity
    }

In the above snippet, where the user is not found, a response of status code 404 will be returned with the following body:


{
   "type": "UserNotFoundError",
   "title": "User Not Found Error",
   "status": 404,
   "detail": "The error is thrown because the requested resource of type `User` could not be found",
   "instance": "/users/123",
   "data": {
       "userId": 123
   }
}

The XML comments for the class will be used to generate the detail information about the error. It can be useful if you use the UI package, as the error information can be obtain via the UI.

Product Compatible and additional computed target framework versions.
.NET net8.0 is compatible.  net8.0-android was computed.  net8.0-browser was computed.  net8.0-ios was computed.  net8.0-maccatalyst was computed.  net8.0-macos was computed.  net8.0-tvos was computed.  net8.0-windows was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.
  • net8.0

    • No dependencies.

NuGet packages (4)

Showing the top 4 NuGet packages that depend on DotNetBrightener.AspNet.Extensions.SelfDocumentedProblemResult:

Package Downloads
DotNetBrightener.WebApi.GenericCRUD

Package Description

DotNetBrightener.WebApp.CommonShared

Package Description

DotNetBrightener.LocaleManagement

Package Description

DotNetBrightener.AspNet.Extensions.SelfDocumentedProblemResult.UI

Package Description

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last updated
2024.0.14.6-rc-243031001 116 10/29/2024
2024.0.14.6-rc-243030701 104 10/29/2024
2024.0.14.6-rc-242840501 97 10/10/2024
2024.0.14.6-rc-242820305 105 10/8/2024
2024.0.14.6-rc-242771401 199 10/3/2024
2024.0.14.6-rc-242770501 105 10/3/2024
2024.0.14.6-rc-242770201 109 10/3/2024
2024.0.14.6-rc-242761801 98 10/2/2024
2024.0.14.6-rc-242761601 120 10/2/2024
2024.0.14.6-rc-242761501 96 10/2/2024
2024.0.14.6-rc-242761401 108 10/2/2024
2024.0.14.6-rc-242760701 118 10/2/2024
2024.0.14.6-rc-242751002 105 10/1/2024
2024.0.14.6-rc-242750901 132 10/1/2024
2024.0.14.6-rc-242750502 105 10/1/2024
2024.0.14.6-rc-242750201 95 10/1/2024
2024.0.14.6-rc-242741501 107 9/30/2024
2024.0.14.6-rc-242730701 132 9/29/2024
2024.0.14.6-preview-2730501 100 9/29/2024
2024.0.14.6-preview-2701501 146 9/26/2024
2024.0.14.6-preview-2620901 153 9/18/2024
2024.0.14.6-preview-2570701 108 9/13/2024
2024.0.14.6-preview-2510703 173 9/7/2024
2024.0.14.6-preview-2480501 145 9/4/2024
2024.0.14.6-preview-2430401 154 8/30/2024
2024.0.14.6-preview-242730701 105 9/29/2024
2024.0.14.6-preview-2421703 116 8/29/2024
2024.0.14.6-preview-2421701 108 8/29/2024
2024.0.14.6-preview-2420901 111 8/29/2024
2024.0.14.6-preview-2390101 137 8/26/2024
2024.0.14.6-preview-2381603 138 8/25/2024
2024.0.14.6-preview-2341601 149 8/21/2024
2024.0.14.6-preview-2321602 131 8/20/2024
2024.0.14.6-preview-2190801 166 8/6/2024
2024.0.14.6-preview-2041501 108 7/22/2024
2024.0.14.6-preview-1920603 183 7/10/2024
2024.0.14.6-preview-1920301 115 7/10/2024
2024.0.14.6-preview-1911302 132 7/9/2024
2024.0.14.6-preview-1901001 129 7/8/2024
2024.0.14.6-preview-1900901 118 7/8/2024
2024.0.14.6-preview-1900801 114 7/8/2024
2024.0.14.6-preview-1860304 103 7/4/2024
2024.0.14.5 164 7/1/2024
2024.0.14.5-preview-1811601 113 6/29/2024
2024.0.14.5-preview-1810501 132 6/29/2024
2024.0.14.5-preview-180132 120 6/28/2024
2024.0.14.5-preview-180131 105 6/28/2024
2024.0.14.5-preview-180121 100 6/28/2024
2024.0.14.4 127 6/27/2024
2024.0.14.4-preview-8 90 6/27/2024
2024.0.14.4-preview-7 111 6/27/2024
2024.0.14.4-preview-6 85 6/27/2024
2024.0.14.3 122 6/21/2024
2024.0.14.1 118 6/6/2024
2024.0.14.1-preview 99 6/6/2024
2024.0.14-preview-1 107 6/6/2024
2024.0.13.8-preview 113 6/6/2024
2024.0.13.2-preview-247 82 6/6/2024
2024.0.13.1-preview-0146 98 6/6/2024
2024.0.13-preview-1 94 6/6/2024
2024.0.12.15803-preview-03 110 6/6/2024
2024.0.12.15608 126 6/4/2024
2024.0.12.15515 188 6/3/2024
2024.0.12.15220 106 5/31/2024
2024.0.12.15220-alpha31-240... 85 5/31/2024
2024.0.12.14911 152 5/28/2024
2024.0.12.14910-alpha28-240... 96 5/28/2024
2024.0.12.14823 123 5/27/2024
2024.0.12.14522-alpha7-2405... 108 5/24/2024
2024.0.12.14514-alpha6-2405... 110 5/24/2024
2024.0.12.14511 137 5/24/2024
2024.0.12.14314 174 5/22/2024
2024.0.12.14114 153 5/20/2024
2024.0.12.12815 162 5/7/2024
2024.0.12.12814 117 5/7/2024
2024.0.12.12721 149 5/6/2024
2024.0.12.12702 135 5/5/2024
2024.0.12.12622 152 5/5/2024
2024.0.12.12514 125 5/4/2024
2024.0.12.12512 139 5/4/2024
2024.0.12.12510 145 5/4/2024
2024.0.12.12420 107 5/3/2024
2024.0.12.12319 94 5/2/2024
2024.0.12.12319-rc-2405021801 83 5/2/2024
2024.0.12.12318 88 5/2/2024
2024.0.12.12215 134 5/1/2024
2024.0.12.12011 145 4/29/2024
2024.0.12.11720 148 4/26/2024
2024.0.12.11719 144 4/26/2024
2024.0.12.11621 151 4/25/2024
2024.0.12.11523 132 4/24/2024
2024.0.12.11522 146 4/24/2024
2024.0.12.11417 138 4/23/2024
2024.0.12.11400 143 4/22/2024
2024.0.12.11316 147 4/22/2024
2024.0.11.10220 140 4/11/2024
2024.0.11.10120 129 4/10/2024
2024.0.11.10119 108 4/10/2024
2024.0.11.10115 118 4/10/2024
2024.0.11.9914 163 4/8/2024
2024.0.11.9901 129 4/7/2024
2024.0.11.9823 147 4/7/2024
2024.0.11.9401 156 4/2/2024
2024.0.11.9301 128 4/1/2024
2024.0.11.9206 157 3/31/2024
2024.0.11.9205 147 3/31/2024