How to Handle Exception Globally in ASP.NET Core application

Problem Defination :- We have a requirement in which we need to Handle an exception thrown by an application in ASP .Net Core . For example while implementing any functionality in application if developer forgot the write the code for exception handling then you will get an exception on production also that it not a good practice so here we are writting some middileware for handling the global exception from code.

In ASP.Net core we can handle exception in many ways but in this article I am going to explain it by an custom middileware to handle the exception using the request delegate. Below is the step by step process explain in details so that you can follow it and create a Web API project so that we can learn the exception handling in asp.net core.

Create a Web API Project using Microsoft Visual Studio
Select Project Type ASP.Net Core Web API and click on OK the you should be able to see below image for solution explorer.

Your Solution explorer looks like as in image

Image is not available

Install the required packages from nuget package manager , in our case we required Newtonsoft.Json.

Create a Model Folder and create a model class category for data manipulation and other model class Errordetails for details of errors.

                    
public class Category
    {
        public int Id { get; set; }
        public string Name { get; set; }
    } 
                    
  public class ErrorDetails
    {
        public string Title { get; set; }
        public string Status { get; set; }
    } 

Create a Controller and named it for exceptionTest and write down below code for testing the exception in application.

Image is not available
                    
 [Route("api/[controller]")]
    [ApiController]
    public class ExceptionTestController : ControllerBase
    {
        [HttpGet]
        public IActionResult GetCategories()
        {
            throw new NotImplementedException();
            return Ok();
        }
        [HttpGet("id")]
        public IActionResult GetCategoriesbyId(int id)
        {
            List categories = new List();
            categories.Add(new Category { Id = 1, Name = "Product" });
            categories.Add(new Category { Id = 2, Name = "Images" });
            categories.Add(new Category { Id = 3, Name = "Sales" });
            categories.Add(new Category { Id = 4, Name = "Account" });
            var result=categories.Where(c => c.Id == id).First();  
            return Ok(result);
        }
    } 

Create a Class for customizing the exception code and named it for ExceptionMiddileware and write down below code for handling the exception in application. Here we have used a Request Delegate that is used for providing the details to next middileware in asp.net core and we have written a method InvokeAsync for handling the response and customized it through the ErrorDeatils class proerties like tiltle and status of error and then we serialize the object into the Json then write it to the response back as shown into the below image.

Image is not available

You can find the Exception Class code from below.

                    
  public class ExceptionMiddileware
    {
        private readonly RequestDelegate _requestDelegate;
        public ExceptionMiddileware(RequestDelegate requestDelegate)
        {
            _requestDelegate = requestDelegate;
        }
        public async Task InvokeAsync(HttpContext context)
        {
            try
            {
                await _requestDelegate(context);
            }
            catch 
            {
                context.Response.ContentType = "application/problem+json";
                context.Response.StatusCode = StatusCodes.Status500InternalServerError;
                var error = new ErrorDetails
                {
                    Title = "Error into the application code",
                    Status = "Internal Server Error"
                };
                var result = JsonConvert.SerializeObject(error);
                await context.Response.WriteAsync(result);
            }
        }
    } 

Add the Custom Middileware into the application from program.cs file as like in below image and code.

Image is not available
                    
using GlobalExceptionHandling.Middilewares;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.

builder.Services.AddControllers();
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}
app.UseMiddleware();
app.UseAuthorization();
app.MapControllers();
app.Run(); 

Run the application you will get the below response when you will hit the URL for error prone code and we can check that our custom logic for exception handling is working fine globally in asp.net core application , please refer the below image for URL to access the code.

Image is not available

Image is not available

About the Author
Sudheer Singh Chouhan is a Software Engineer having Expertise in Development Design and Architecting the applications , Project Management , Designing Large Scale Databases in SQL Server since last 17 Years.
Skill Sets :- Microsoft .NET technologies like ASP.Net Core, Web API, LINQ, Web Forms, WinForms, SQL Server, EntityFramework, Design Patterns, Solid Principles, Microservices, AWS Cloud.