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.
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:
- BadRequestException
- ConflictException
- ForbiddenException
- NotFoundException
- UnauthorizedException
- InternalServerErrorException
Example:
if (value < 0)
throw new BadRequestException("Value can not be less than 0.");