using Common.Utilities; using djy.Model; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.Logging; using Newtonsoft.Json; using System; using System.Net; using System.Threading.Tasks; namespace djy_AfrApi.Middlewares { public class ExceptionHandlerMiddleware { private readonly RequestDelegate _next; private readonly ILogger logger; public ExceptionHandlerMiddleware(RequestDelegate next, ILogger logger) { _next = next; this.logger = logger; } public async Task Invoke(HttpContext context) { try { //_ = int.Parse(""); await _next(context); } catch (Exception ex) { await HandleExceptionAsync(context, ex); } } private async Task HandleExceptionAsync(HttpContext context, Exception e) { if (e == null) return; logger.LogError(WriteLog("ExceptionHandlerMiddleware中捕获的全局异常", e)); 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(new Response() { Code = 500, Message = message })) .ConfigureAwait(false); } /// /// 自定义返回格式 /// /// /// /// public string WriteLog(string throwMsg, Exception ex) { return string.Format("\r\n【自定义错误】:{0} \r\n【异常类型】:{1} \r\n【异常信息】:{2} \r\n【堆栈调用】:{3}\r\n自定义异常结束", new object[] { throwMsg, ex.GetType().Name, ex.Message, ex.StackTrace }); } } }