Example of using .NET 8 IExceptionHandler to return 7807 ProblemDetails compliant response to client

Dave Callan
2024-03-02T08:46:41Z

GlobalExceptionHandlerProblemDetails.cs

| using Microsoft.AspNetCore.Diagnostics;
| using Microsoft.AspNetCore.Mvc;
| using System.Net;
|
| namespace Samples;
|
| public class GlobalExceptionHandler(ILogger<GlobalExceptionHandler> logger) : IExceptionHandler
| {
| public async ValueTask<bool> TryHandleAsync(
| HttpContext httpContext,
| Exception exception,
| CancellationToken cancellationToken)
| {
| var exceptionMessage = exception.Message;
| logger.LogError(exception,
| "Error Message: {exceptionMessage}, Time of occurrence {time}",
| exceptionMessage, DateTime.UtcNow);
|
| // Return RFC 7807 - compliant payload to the client
| httpContext.Response.StatusCode = (int)HttpStatusCode.BadRequest;
| await httpContext.Response.WriteAsJsonAsync(new ProblemDetails
| {
| Title = "An error occurred",
| Detail = exception.Message,
| Type = exception.GetType().Name,
| Status = (int)HttpStatusCode.BadRequest
| }, cancellationToken: cancellationToken);
|
| // Return false to continue with the default behavior
| // - or - return true to signal that this exception is handled
| return true;
| }
| }
|
| //Program.cs ...
| //var builder = WebApplication.CreateBuilder(args);
| //builder.Services.AddProblemDetails();
|
| //var app = builder.Build();
| //app.UseStatusCodePages();
|
| //app.Run();