Note: Currently, I have implemented two types in this repository, and in the future, other methods will be added.
public async Task InvokeAsync(HttpContext context)
{
try
{
await _next(context);
}
catch (Exception exception)
{
var problemDetails = new ProblemDetails
{
Status = GetStatusCode(exception),
Title = GetTitle(exception),
Type = "Server Error",
Detail = exception.Message
};
context.Response.StatusCode =
StatusCodes.Status500InternalServerError;
await context.Response.WriteAsJsonAsync(problemDetails);
}
}app.UseMiddleware<ExceptionHandlingMiddleware>();In these conditions, any exception thrown in the code will be managed by this middleware wherever it occurs.
internal sealed class GlobalExceptionHandler : IExceptionHandler public async ValueTask<bool> TryHandleAsync(
HttpContext httpContext,
Exception exception,
CancellationToken cancellationToken)
{
_logger.LogError(
exception, "Exception occurred: {Message}", exception.Message);
var problemDetails = new ProblemDetails
{
Status = GetStatusCode(exception),
Title = GetTitle(exception),
Type = "Server Error",
Detail = exception.Message
};
httpContext.Response.StatusCode = problemDetails.Status.Value;
await httpContext.Response
.WriteAsJsonAsync(problemDetails, cancellationToken);
return true;
}builder.Services.AddExceptionHandler<GlobalExceptionHandler>();
builder.Services.AddProblemDetails();app.UseExceptionHandler();