|
@@ -0,0 +1,82 @@
|
|
|
+using Microsoft.AspNetCore.Http;
|
|
|
+
|
|
|
+namespace OASystem.API.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 exception)
|
|
|
+ {
|
|
|
+ context.Response.ContentType = "application/json";
|
|
|
+ var response = context.Response;
|
|
|
+ var errorResponse = new JsonView
|
|
|
+ {
|
|
|
+ Code = StatusCodes.Status400BadRequest,
|
|
|
+ Data = ""
|
|
|
+ };
|
|
|
+ switch (exception)
|
|
|
+ {
|
|
|
+ case ApplicationException ex:
|
|
|
+ if (ex.Message.Contains("Invalid token"))
|
|
|
+ {
|
|
|
+ response.StatusCode = StatusCodes.Status403Forbidden;
|
|
|
+ errorResponse.Msg = ex.Message;
|
|
|
+ break;
|
|
|
+ }
|
|
|
+ response.StatusCode = StatusCodes.Status400BadRequest;
|
|
|
+ errorResponse.Msg = ex.Message;
|
|
|
+ break;
|
|
|
+ case KeyNotFoundException ex:
|
|
|
+ response.StatusCode = StatusCodes.Status404NotFound;
|
|
|
+ errorResponse.Msg = ex.Message;
|
|
|
+ break;
|
|
|
+ default:
|
|
|
+ response.StatusCode = StatusCodes.Status500InternalServerError;
|
|
|
+ errorResponse.Msg = "Internal Server errors. Check Logs!";
|
|
|
+ break;
|
|
|
+ }
|
|
|
+ _logger.LogError(exception.Message);
|
|
|
+ var result = JsonConvert.SerializeObject(errorResponse);
|
|
|
+ await context.Response.WriteAsync(result);
|
|
|
+ }
|
|
|
+ }
|
|
|
+}
|