Implementation Of Global Exception Handling Using .NET Core 6 Web API

Introduction

Implementing global exception handling in a .NET Core 6 Web API involves creating a custom middleware to catch and handle exceptions that occur during the request pipeline. This allows you to centralize error handling and provide consistent responses to clients. Here’s an example of how you can implement global exception handling in a .NET Core 6 Web API:

Step 1: Create Custom Exception Middleware

Create a new class for your custom exception middleware, such as GlobalExceptionHandlerMiddleware.cs:

using Microsoft.AspNetCore.Http;
using Newtonsoft.Json;
using System;
using System.Net;
using System.Threading.Tasks;

public class GlobalExceptionHandlerMiddleware
{
    private readonly RequestDelegate _next;

    public GlobalExceptionHandlerMiddleware(RequestDelegate next)
    {
        _next = next;
    }

    public async Task Invoke(HttpContext context)
    {
        try
        {
            await _next(context);
        }
        catch (Exception ex)
        {
            await HandleExceptionAsync(context, ex);
        }
    }

    private static async Task HandleExceptionAsync(HttpContext context, Exception exception)
    {
        context.Response.ContentType = "application/json";
        context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;

        var response = new
        {
            Message = "An error occurred while processing your request.",
            ExceptionMessage = exception.Message,
            StackTrace = exception.StackTrace
        };

        await context.Response.WriteAsync(JsonConvert.SerializeObject(response));
    }
}

Step 2: Register Custom Middleware

In the Startup.cs file, add the following code to the Configure method to register the custom exception middleware:

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    // ...

    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }
    else
    {
        app.UseExceptionHandler("/Home/Error");
        app.UseHsts();
    }

    app.UseHttpsRedirection();
    app.UseStaticFiles();
    app.UseRouting();

    // Register the custom exception middleware
    app.UseMiddleware<GlobalExceptionHandlerMiddleware>();

    app.UseAuthorization();

    app.UseEndpoints(endpoints =>
    {
        endpoints.MapControllers();
    });
}

Step 3: Test Global Exception Handling

In your controllers, you can throw exceptions to test the global exception handling. For example:

using Microsoft.AspNetCore.Mvc;
using System;

[ApiController]
[Route("api/[controller]")]
public class TestController : ControllerBase
{
    [HttpGet("throw")]
    public IActionResult ThrowException()
    {
        throw new ApplicationException("This is a test exception.");
    }

    [HttpGet("handled")]
    public IActionResult HandledException()
    {
        try
        {
            throw new ApplicationException("This is a handled exception.");
        }
        catch (Exception ex)
        {
            // Log or handle the exception as needed
            return BadRequest(ex.Message);
        }
    }
}

Step 4: Test the API

Run your Web API, and then use a tool like Postman to make requests to the TestController endpoints:

  1. GET /api/test/throw: This endpoint will trigger an unhandled exception, which will be caught and processed by the custom exception middleware.
  2. GET /api/test/handled: This endpoint will throw an exception that is caught and handled within the controller method. The custom middleware won’t be invoked in this case.

Summary

By implementing custom exception middleware, you can achieve global exception handling in your .NET Core 6 Web API. This centralizes the handling of exceptions and ensures consistent error responses to clients. Remember to customize the exception-handling logic, error messages, and status codes based on your specific application needs.

Leave a Reply

Your email address will not be published. Required fields are marked *