GlobalExceptionHandler.cs 869 B

123456789101112131415161718192021222324252627
  1. using Microsoft.AspNetCore.Diagnostics;
  2. using Microsoft.AspNetCore.Mvc;
  3. namespace Web.Api.Common;
  4. internal sealed class GlobalExceptionHandler(ILogger<GlobalExceptionHandler> logger) : IExceptionHandler
  5. {
  6. public async ValueTask<bool> TryHandleAsync(
  7. HttpContext httpContext,
  8. Exception exception,
  9. CancellationToken cancellationToken)
  10. {
  11. logger.LogError(exception, "Unhandled exception occurred");
  12. var problemDetails = new ProblemDetails
  13. {
  14. Status = StatusCodes.Status500InternalServerError,
  15. Type = "https://tools.ietf.org/html/rfc7231#section-6.6.1",
  16. Title = "Server failure"
  17. };
  18. httpContext.Response.StatusCode = problemDetails.Status.Value;
  19. await httpContext.Response.WriteAsJsonAsync(problemDetails, cancellationToken);
  20. return true;
  21. }
  22. }