47 lines
1.9 KiB
C#
47 lines
1.9 KiB
C#
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<IExceptionHandlerFeature>();
|
|
if (exceptionFeature is null) return;
|
|
|
|
var exception = exceptionFeature.Error;
|
|
var ticketId = Guid.NewGuid().ToString();
|
|
|
|
context.RequestServices
|
|
.GetRequiredService<ILoggerFactory>()
|
|
.CreateLogger("GlobalExceptionHandler")
|
|
.LogError($"Global exception occurs (TicketId {ticketId}).{Environment.NewLine}{exception}");
|
|
|
|
var transformation = context.RequestServices
|
|
.GetServices<IExceptionTransformation>()
|
|
.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<IHttpResponseFeature>().ReasonPhrase = info.ReasonPhrase;
|
|
await context.Response.WriteAsync(info.Details ?? string.Empty);
|
|
});
|
|
});
|
|
|
|
return app;
|
|
}
|
|
}
|