DEV Community

Cover image for How to handle global exception in .NET Core
neophyte
neophyte

Posted on

How to handle global exception in .NET Core

In ASP.NET Core, you can handle global exceptions using middleware. Middleware is a component that sits in the request pipeline and can perform tasks before or after the request reaches your controller actions. Handling global exceptions through middleware allows you to centralize error handling and provide consistent behavior for your application.

Here's how you can create middleware to handle global exceptions in .NET Core:

  1. Create a Middleware Class:

Create a new class for your middleware. This class should have a constructor that takes in RequestDelegate, which represents the next delegate in the pipeline. Inside the class, you can catch and handle exceptions.

public sealed class GlobalErrorHandlingMiddleware
{
    private readonly ILogger<GlobalErrorHandlingMiddleware> _logger;
    private readonly RequestDelegate _next;

    public GlobalErrorHandlingMiddleware(ILogger<GlobalErrorHandlingMiddleware> logger, RequestDelegate next)
    {
        _logger = logger;
        _next = next;
    }

    public async Task InvokeAsync(HttpContext context)
    {
        try
        {

            await _next(context);
        }
        catch(Exception ex)
        {
            _logger.LogError(ex, ex.Message);
            context.Response.ContentType = "application/json";
            context.Response.StatusCode = StatusCodes.Status500InternalServerError;
            await context.Response.WriteAsync("An error occurred.");
        }
    }
}
Enter fullscreen mode Exit fullscreen mode
  1. Register Middleware: In your program.cs class, add the middleware, GlobalExceptionMiddleware before registering MVC or routing middleware. This ensures that the exception handling middleware is executed for all requests.
app.UseMiddleware<GlobalErrorHandlingMiddleware>();
Enter fullscreen mode Exit fullscreen mode

By placing the UseMiddleware() call in the appropriate position, you ensure that any unhandled exceptions thrown within the pipeline will be caught by your custom middleware and handled according to your logic.

Thanks for reading.

Top comments (0)