Skip to content

exp1azy/exception_middleware

Repository files navigation

AspNetCore.ExceptionMiddleware

Provides a custom middleware that generates an RFC response when an exception occurs, allowing you to unify error handling and response style, which simplifies debugging on both the client and server sides.

Usage

Just use ExceptionMiddleware as a custom middleware in the Program.cs class:

using AspNetCore.ExceptionMiddleware; // specify the namespace

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddControllers();

var app = builder.Build();

app.MapControllers();
app.UseMiddleware<ExceptionMiddleware>(); // specify the exception handler
app.Run();

After that, you will receive a clean and understandable error response:

{
    "Type": "https://tools.ietf.org/html/rfc7231#section-6.5.8", // official documentation on the error
    "Title": "Conflict", // a short, human-readable default description of the problem for this HTTP status
    "Status": 409, // HTTP status code
    "Detail": "There was a conflict when executing the request.", // your own error description message
    "Instance": "/test/conflict/false" // the endpoint where the exception occurred
}

Depending on the error that occurred, you can use several exceptions:

  1. BadRequestException
  2. ConflictException
  3. ForbiddenException
  4. NotFoundException
  5. UnauthorizedException
  6. InternalServerErrorException

Example:

if (value < 0)
    throw new BadRequestException("Value can not be less than 0.");

About

No description, website, or topics provided.

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages