How to Handle Exceptions Globally in an ASP.NET Core Application
Problem definition: We need to handle exceptions thrown by an ASP.NET Core application. For example, if a developer forgets to write exception-handling code for a feature, users see an unhandled exception in production, which is bad practice. So here we write middleware that handles exceptions globally.
In ASP.NET Core we can handle exceptions in many ways. In this article, I explain how to do it with custom middleware that uses the request delegate. Below is the step-by-step process, explained in detail, so that you can create a Web API project and learn exception handling in ASP.NET Core.
Create a Web API project in Microsoft Visual Studio
Select the ASP.NET Core Web API project type and click OK. Your Solution Explorer will look like the image below.
Your Solution Explorer looks like the image below.
Install the required packages from the NuGet Package Manager. In our case, we need Newtonsoft.Json.
Create a Models folder with a model class Category for the data, and another model class ErrorDetails for the error details.
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 named ExceptionTest and write the code below to test exceptions in the application.
[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<Category> categories = new List<Category>();
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 the custom exception handling, name it ExceptionMiddleware, and write the code below to handle exceptions in the application. Here we use a request delegate, which passes the request to the next middleware in ASP.NET Core, and an InvokeAsync method that builds the response using the ErrorDetails class properties, such as the title and status of the error. We then serialize the object to JSON and write it to the response, as shown in the image below.
You can find the exception class code 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 middleware to the application in the Program.cs file, as shown in the image and code below.
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<ExceptionMiddileware>();
app.UseAuthorization();
app.MapControllers();
app.Run();
Run the application. When you call the URL for the error-prone code, you get the response below, which confirms that our global exception handling works in the ASP.NET Core application. See the image below for the URL.