در ASP.NET Core 8.0 نیز امکان مدیریت استثناءها به صورت سراسری با پیادهسازی اینترفیس
IExceptionHandler مسیر شده است: using Microsoft.AspNetCore.Diagnostics;
using Microsoft.AspNetCore.Mvc;
internal sealed class GlobalExceptionHandler : IExceptionHandler
{
private readonly ILogger<GlobalExceptionHandler> _logger;
public GlobalExceptionHandler(ILogger<GlobalExceptionHandler> logger)
{
_logger = logger;
}
public async ValueTask<bool> TryHandleAsync(
HttpContext context,
Exception exception,
CancellationToken cancellationToken = default)
{
_logger.LogError(exception, "An unhandled exception has occurred while executing the request.");
var problemDetails = new ProblemDetails
{
Status = StatusCodes.Status500InternalServerError,
Title = "Server Error",
};
context.Response.StatusCode = StatusCodes.Status500InternalServerError;
await context.Response.WriteAsJsonAsync(problemDetails);
return true;
}
}
برای ریجستر کردن آن نیز:
builder.Services.AddExceptionHandler<GlobalExceptionHandler>();
// other code
app.UseExceptionHandler();