GlobalExceptionHandler.cs 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  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. if (exception is BadHttpRequestException)
  11. {
  12. logger.LogWarning(exception, "Bad request");
  13. httpContext.Response.StatusCode = StatusCodes.Status400BadRequest;
  14. httpContext.Response.ContentType = "application/json";
  15. await httpContext.Response.WriteAsJsonAsync(new ApiResponse
  16. {
  17. Success = false,
  18. Status = StatusCodes.Status400BadRequest,
  19. Message = "Invalid request body"
  20. }, cancellationToken);
  21. return true;
  22. }
  23. logger.LogError(exception, "Unhandled exception occurred");
  24. httpContext.Response.StatusCode = StatusCodes.Status500InternalServerError;
  25. httpContext.Response.ContentType = "application/json";
  26. await httpContext.Response.WriteAsJsonAsync(new ApiResponse
  27. {
  28. Success = false,
  29. Status = StatusCodes.Status500InternalServerError,
  30. Message = "Server failure"
  31. }, cancellationToken);
  32. return true;
  33. }
  34. }