Install-Package CustomExceptionMiddleware
dotnet add package CustomExceptionMiddleware
Minimum requirements to use: .NET Standard 2.0
Compilation requirements: .NET 5
It's very simple to use, go to Startup.cs
on Configure()
method and add this code:
app.UseCustomExceptionMiddleware();
Example output
{
"ErrorMessage": "Custom not found exception message"
}
-
Create object options
It's possible create aCustomExceptionOptions
to customize the return middleware object, to create this options add this:app.UseCustomExceptionMiddleware(new CustomExceptionOptions { CustomErrorModel = new { Success = false Type = "ErrorType" } });
Example output
{ "Type": "TestType", "Success": false, "ErrorMessage": "Custom not found exception message" }
-
Use an action options
Other options to customize the return object is using an action to create aCustomErrorModel
app.UseCustomExceptionMiddleware(options => { options.CustomErrorModel = new { Success = false Type = "ErrorType" }; });
Example output
{ "Type": "TestType", "Success": false, "ErrorMessage": "Custom not found exception message" }
This middleware use some custom exceptions to catch and personalize the response status code.
The custom middleware supports the following Exceptions:
Exception | Status code description | Status code |
---|---|---|
DomainException | BadRequest | 400 |
CannotAccessException | Forbidden | 403 |
NotFoundException | NotFound | 404 |
Exception | InternalServerError | 500 |
DomainException
is an abstract exception, so to use it's necessary create other exception and inherit. The others exceptions only throw an exception
public class InvalidStateException : DomainException
{
public InvalidStateException(string message) : base(message)
{ }
}
throw new InvalidStateException("Custom domain exception message");
throw new CannotAccessException("Custom cannot access exception message");
throw new NotFoundException("Custom not found exception message");
throw new Exception("Custom exception message");