using System.Net; using GerstITS.Web.Api.ExceptionHandling; using Microsoft.AspNetCore.Diagnostics; using Microsoft.AspNetCore.Http.Features; namespace GerstITS.Examples.Api.ExceptionHandling; internal static class WebApplicationExtensions { internal static WebApplication UseGlobalExceptionHandling(this WebApplication app) { app.UseExceptionHandler(exceptionHandlerApp => { exceptionHandlerApp.Run(async context => { var exceptionFeature = context.Features.Get(); if (exceptionFeature is null) return; var exception = exceptionFeature.Error; var ticketId = Guid.NewGuid().ToString(); context.RequestServices .GetRequiredService() .CreateLogger("GlobalExceptionHandler") .LogError($"Global exception occurs (TicketId {ticketId}).{Environment.NewLine}{exception}"); var transformation = context.RequestServices .GetServices() .FirstOrDefault(x => x.CanTransform(exception)); var info = transformation?.Transform(exception, ticketId) ?? new ExceptionTransformationInfo { StatusCode = HttpStatusCode.InternalServerError, ReasonPhrase = "Internal Server Error.", Details = $"An internal error occurs. Please contact support with ticket id '{ticketId}'." }; context.Response.StatusCode = (int)info.StatusCode; context.Features.Get().ReasonPhrase = info.ReasonPhrase; await context.Response.WriteAsync(info.Details ?? string.Empty); }); }); return app; } }