Global Exception Handling in Asp.Net Core Web Api

Introduction

Exception handling deals with undesirable and unaddressed errors that can crash your system; hence, it is one of the crucial processes of any programming language.

In this article, we are going to learn how to implement Global Exception Handling in Asp.Net Core WebAPI.

There are many ways available to implement Global Exception Handling in Asp.Net Core WebApi. In this article, we are going to discuss how to implement Global exceptions using Custom Middleware.

This article can be used by Beginner, Intermediate, and Experienced.

Prerequisite

  1. Visual Studio 2022
  2. Understanding of Middleware
  3. Understanding of CustomMiddleware

Custom Middleware 

I hope you have a good understanding of Middleware and CustomMiddelware. If you don't, I recommend that you please read Middleware and CustomMiddleware first and then proceed to read Global Exception Handling in Asp.Net WebApi.

Step 1. Create Asp.Net WebApi project”.

Step 2. Add new Middleware class “ExceptionMiddleware.cs”.

public class ExceptionMiddleware
{
    private readonly RequestDelegate _next;

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

    public async Task InvokeAsync(HttpContext httpContext)
    {
        try
        {
            await _next(httpContext);
        }
        catch (Exception ex)
        {
            httpContext.Response.ContentType = "application/json";
            httpContext.Response.StatusCode = (int)HttpStatusCode.InternalServerError;

            var problem = new ProblemDetails
            {
                Status = httpContext.Response.StatusCode,
                Title = ex.Message,
            };

            await httpContext.Response.WriteAsync(JsonSerializer.Serialize(problem));
        }
    }

    public static class MiddlewareExtensions
    {
        public static IApplicationBuilder UseExceptionMiddleware(this IApplicationBuilder builder)
        {
            return builder.UseMiddleware<ExceptionMiddleware>();
        }
    }
}

Step 3. Register Middleware in the program.cs file.

app.UseExceptionMiddleware(); 
app.Run();

Ensure that you either comment out or remove the UseExceptionHandler default middleware, as it could lead to undesirable conflicts. It isn't logical to have several middleware performing the same function, right?

Step 4. Let’s throw an exception from the WeatherForecastController for demo purposes.

We are throwing exceptions from the Get endpoint.

[ApiController]
[Route("[controller]")]
public class WeatherForecastController : ControllerBase
{
    private static readonly string[] Summaries = new[]
    {
        "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
    };

    private readonly ILogger<WeatherForecastController> logger;

    public WeatherForecastController(ILogger<WeatherForecastController> logger)
    {
        _logger = logger;
    }

    [HttpGet(Name = "GetWeatherForecast")]
    public IEnumerable<WeatherForecast> Get()
    {
        throw new Exception("Weather issue");
    }
}

Step 5. Let’s execute and see the output.

You will see the Error message as output.

Error message

This is the best way to implement Global Exception handing in Asp.Net Core 7 Web Api. In the next article, we will explore how to implement global exception handling.

I hope you have learned and enjoyed this article.