Global Exception Handler ASP.NET Core 8
ASP .NET Core Project for learning. Every one should be able to use this templae to build a ASP .NET Core web API with global exception handler. 0 commentsBy Sopheaktra Eang | May 23, 2024
- API
- Swagger for API's Endpoint
Why we need to use global exception?
Because global exception handling ensures that every exception is caught and appropriate details related to the exception are returned.
What is benefit of it?
- Benefits:
- Consistent Error Responses: A global handler ensures that all exceptions return consistent error responses (e.g., HTTP status codes, error messages).
- Centralized Exception Logging: You can log exceptions centrally for monitoring and debugging purposes.
These instructions will get you to setup the project, install sdk and add package (CLI or Package manager console).
- Visual Studio 2022 or higher
- .NET 8.x SDK
- Install .net SDK 8
Download .NET SDK here. - Create new Web API's project (Please create main project with empty and add below to the main project)
dotnet new webapi –-name Global-Exception
- Swagger UI: (http://localhost:5230/swagger/index.html)
Coding
Create our global Response.cs
using Microsoft.AspNetCore.Mvc;
namespace SampleExceptionHandler.Payload.Response{
public class Response : ProblemDetails {
public IDictionary<string, object?>? Data { get; set; }
public IDictionary<string, string[]>? Errors { get; set; }
}
}
Override our Program.cs
using FluentValidation;
using Microsoft.AspNetCore.Mvc;
using SampleExceptionHandler.ExceptionHandler;
using SampleExceptionHandler.Filter;
using SampleExceptionHandler.Payload.Request;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
//add ExceptionHandler
builder.Services.AddExceptionHandler<GlobalExceptionHandler>();
builder.Services.AddProblemDetails();
builder.Services.AddValidatorsFromAssemblyContaining<Program>();
var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
app.UseHttpsRedirection();
var summaries = new[]
{
"Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
};
app.MapGet("/weatherforecast", () =>
{
var forecast = Enumerable.Range(1, 5).Select(index =>
new WeatherForecast
(
DateOnly.FromDateTime(DateTime.Now.AddDays(index)),
Random.Shared.Next(-20, 55),
summaries[Random.Shared.Next(summaries.Length)]
))
.ToArray();
return forecast;
})
.WithName("GetWeatherForecast")
.WithOpenApi();
app.MapPost("/customers", ([FromBody] RegisterCustomerRequest customer) =>
{
// do the thing
return Results.Ok();
})
.AddEndpointFilter<ValidationFilter<RegisterCustomerRequest>>();
app.UseExceptionHandler();
app.Run();
record WeatherForecast(DateOnly Date, int TemperatureC, string? Summary)
{
public int TemperatureF => 32 + (int)(TemperatureC / 0.5556);
}
Note: for dotnet 8+ will have AddExceptionHandler by default and if you are using below the version will need to implement middleware for handle exception as global.
Next session will talk about below version 8 with customize middleware for handle our exception as global.
Languages and Tools
Summary
Download the source code for the sample application implementing an API With Global Exception Handler. After this tutorial you will can handle exception as global with different error message customize.