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.
Eang Sopheaktra
May 26 2024 06:03 pm
Because global exception handling ensures that every exception is caught and appropriate details related to the exception are returned.
These instructions will get you to setup the project, install sdk and add package (CLI or Package manager console).
dotnet new webapi –-name Global-Exception
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.
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.