Techiehook Techiehook
Updated date Jul 02, 2024
In this article, we will learn how to implement global exception handling in ASP.NET Core (.NET 8) applications using custom middleware to catch, log, and send unexpected errors to users with user-friendly messages.

Download File(s):

ExceptionHandlingApi.rar

Handling exceptions globally in ASP.NET Core is important for building strong applications that can easily handle errors and provide meaningful messages to users.

In this article. We will see the steps to set up global exception handling in ASP.NET Core (.Net 8) using custom middleware to catch, log, and send unexpected errors to users with user-friendly messages.

1. Create a new ASP.NET Core project

Create a new project using the "ASP.NET Core Web API" template with.Net 8 and click create.

2. Create the Custom Middleware

Add a new file ExceptionHandlingMiddleware.cs in the project and copy the code below:

using System.Net;

namespace ExceptionHandlingApi
{
    public class ExceptionHandlingMiddleware
    {
        private readonly RequestDelegate _next;
        private readonly ILogger<ExceptionHandlingMiddleware> _logger;

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

        public async Task InvokeAsync(HttpContext context)
        {
            try
            {
                await _next(context);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "An unhandled exception has occurred.");
                await HandleExceptionAsync(context, ex);
            }
        }

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

            var response = new
            {
                message = "An unexpected error occurred. Please try again later.",
                detail = exception.Message
            };

            return context.Response.WriteAsJsonAsync(response);
        }
    }

}

3. Configure the Middleware

In the Program.cs file, configure the middleware as shown below:

using ExceptionHandlingApi;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.

builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

var app = builder.Build();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

// Configure Exception Handling Middleware
app.UseMiddleware<ExceptionHandlingMiddleware>();

app.UseHttpsRedirection();

app.UseAuthorization();

app.MapControllers();

app.Run();

4. Add Method in Controller

Add a simple method to test the global exception handling code. Update the existing WeatherForecastController.cs in the Controllers folder with below Get() method:

using Microsoft.AspNetCore.Mvc;

namespace ExceptionHandlingApi.Controllers
{
    [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]
        public IActionResult Get()
        {
            throw new Exception("Test exception");
        }
    }
}

6. Run and Test the Exception Handling

You can navigate to https://localhost:44395/WeatherForecast/ in your browser or Postman to send a GET request. You should receive a JSON response indicating an error has occurred, and the exception should be logged as shown below. The "detail" will be the exception message we added in the controller method and the "message" from the middleware.

Any unexpected errors (like internal server error, bad request, not found) in your ASP.NET Core application are caught by the middleware, recorded in the logs, and a clear error message is sent back to the user.

ABOUT THE AUTHOR

Techiehook
Techiehook
Admin, Australia

Welcome to TechieHook.com! We are all about tech, lifestyle, and more. As the site admin, I share articles on programming, tech trends, daily life, and reviews... For more detailed information, please check out the user profile

https://www.techiehook.com/profile/alagu-mano-sabari-m

Comments (0)

There are no comments. Be the first to comment!!!