| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657 |
- using AutoMapper;
- using Diligent.WebAPI.Host.Exceptions;
- using Microsoft.IdentityModel.Tokens;
- using System;
- using System.Net;
- using System.Security.Authentication;
-
- namespace Diligent.WebAPI.Host.Middlewares
- {
- public class ExceptionHandlingMiddleware
- {
- private readonly RequestDelegate _next;
- private readonly ILogger<ExceptionHandlingMiddleware> _logger;
-
- public ExceptionHandlingMiddleware(RequestDelegate next, ILogger<ExceptionHandlingMiddleware> logger)
- {
- _next = next;
- _logger = logger;
- }
- public async Task InvokeAsync(HttpContext httpContext)
- {
- try
- {
- await _next(httpContext);
- }
- catch (Exception ex)
- {
- await HandleExceptionAsync(httpContext, ex);
- }
- }
- private async Task HandleExceptionAsync(HttpContext context, Exception ex)
- {
- context.Response.ContentType = "application/json";
-
- context.Response.StatusCode = ex switch
- {
- NotFoundException => (int)HttpStatusCode.NotFound,
- KeyNotFoundException => (int)HttpStatusCode.NotFound,
- BadHttpRequestException => (int)HttpStatusCode.BadRequest,
- SecurityTokenValidationException => (int)HttpStatusCode.InternalServerError,
- AuthenticationException => (int)HttpStatusCode.InternalServerError,
- UnauthorizedAccessException => (int)HttpStatusCode.InternalServerError,
- ArgumentNullException => (int)HttpStatusCode.InternalServerError,
- //...
- _ => (int)HttpStatusCode.InternalServerError
- };
-
- _logger.LogError(ex.Message);
-
- await context.Response.WriteAsync(new ErrorDetails()
- {
- StatusCode = context.Response.StatusCode,
- Message = ex.Message
- }.ToString());
- }
- }
- }
|