How to handle all exceptions in ASP.NET Core 3.1?
Dung Do Tien Dec 28 2020 51
I have a small project which has a lot of classes based on ASP.NET Core 3.1
Sometimes, In a few business classes, the system throws an unhandled exception and I don't want it happens
So, How can I handle all exception throw from my system
Have 1 answer(s) found.
- 0
Firstly, you can extend
ExceptionFilterAttribute
class to custom exception handler for my projectAfter that, you have to register it global in
Startup.cs
Here is my example
I have
ApiExceptionFilter
extendExceptionFilterAttribute
public class ApiExceptionFilter : ExceptionFilterAttribute { public override void OnException(ExceptionContext context) { //Here is your logic code. In my example, I return Status Code 500 var details = new ProblemDetails { Status = StatusCodes.Status500InternalServerError, Title = "An error occurred while processing your request.", Type = "https://tools.ietf.org/html/rfc7231#section-6.6.1" }; context.Result = new ObjectResult(details) { StatusCode = StatusCodes.Status500InternalServerError }; context.ExceptionHandled = true; base.OnException(context); } }
After that, register
ApiExceptionFilter
inStartup.cs
services.AddControllers(config => { config.Filters.Add(typeof(ApiExceptionFilter)); });
I hope it helps you resolve your idea
Dũng Đô La Dec 28 2020
* Type maximum 2000 characters.
* All comments have to wait approved before display.
* Please polite comment and respect questions and answers of others.