From b2ad000e07e1c87d3561b5aa94fdc88c779872f0 Mon Sep 17 00:00:00 2001 From: dengjunjie <dengjunjie@hnkhzn.com> Date: 星期二, 18 二月 2025 22:34:54 +0800 Subject: [PATCH] 1 --- 项目代码/WMS/WIDESEA_WMSServer/WIDESEA_Core/Middlewares/ExceptionHandlerMiddleware.cs | 59 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 files changed, 59 insertions(+), 0 deletions(-) diff --git "a/\351\241\271\347\233\256\344\273\243\347\240\201/WMS/WIDESEA_WMSServer/WIDESEA_Core/Middlewares/ExceptionHandlerMiddleware.cs" "b/\351\241\271\347\233\256\344\273\243\347\240\201/WMS/WIDESEA_WMSServer/WIDESEA_Core/Middlewares/ExceptionHandlerMiddleware.cs" new file mode 100644 index 0000000..33d8e0d --- /dev/null +++ "b/\351\241\271\347\233\256\344\273\243\347\240\201/WMS/WIDESEA_WMSServer/WIDESEA_Core/Middlewares/ExceptionHandlerMiddleware.cs" @@ -0,0 +1,59 @@ +锘縰sing Microsoft.AspNetCore.Http; +using Newtonsoft.Json; +using System; +using System.Collections.Generic; +using System.DirectoryServices.Protocols; +using System.Linq; +using System.Net; +using System.Text; +using System.Threading.Tasks; + +namespace WIDESEA_Core.Middlewares +{ + public class ExceptionHandlerMiddleware + { + private readonly RequestDelegate _next; + + public ExceptionHandlerMiddleware(RequestDelegate next) + { + _next = next; + } + + public async Task Invoke(HttpContext context) + { + try + { + await _next(context); + } + catch (Exception ex) + { + await HandleExceptionAsync(context, ex); + } + } + + private async Task HandleExceptionAsync(HttpContext context, Exception e) + { + if (e == null) return; + + await WriteExceptionAsync(context, e).ConfigureAwait(false); + } + + private static async Task WriteExceptionAsync(HttpContext context, Exception e) + { + var message = e.Message; + switch (e) + { + case UnauthorizedAccessException: + context.Response.StatusCode = (int)HttpStatusCode.Unauthorized; + break; + default: + context.Response.StatusCode = (int)HttpStatusCode.InternalServerError; + break; + } + context.Response.ContentType = "application/json"; + await context.Response + .WriteAsync(JsonConvert.SerializeObject(WebResponseContent.Instance.Error(message))) + .ConfigureAwait(false); + } + } +} -- Gitblit v1.9.3