GlobalExceptionHandler.cs 823 B

1234567891011121314151617181920212223242526
  1. using Microsoft.AspNetCore.Diagnostics;
  2. namespace Web.Api.Common;
  3. internal sealed class GlobalExceptionHandler(ILogger<GlobalExceptionHandler> logger) : IExceptionHandler
  4. {
  5. public async ValueTask<bool> TryHandleAsync(
  6. HttpContext httpContext,
  7. Exception exception,
  8. CancellationToken cancellationToken)
  9. {
  10. logger.LogError(exception, "Unhandled exception occurred");
  11. httpContext.Response.StatusCode = StatusCodes.Status500InternalServerError;
  12. httpContext.Response.ContentType = "application/json";
  13. await httpContext.Response.WriteAsJsonAsync(new ApiResponse
  14. {
  15. Success = false,
  16. Status = StatusCodes.Status500InternalServerError,
  17. Message = "Server failure"
  18. }, cancellationToken);
  19. return true;
  20. }
  21. }