using Microsoft.AspNetCore.Http; using Newtonsoft.Json; using System.Net; using Znyc.CloudCar.Model.ViewModels.ReportsCallBack; namespace Znyc.CloudCar.Middlewares { /// /// 异常错误统一返回记录 /// public class ExceptionHandlerMid { private readonly RequestDelegate _next; public ExceptionHandlerMid(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 ex) { if (ex == null) return; await WriteExceptionAsync(context, ex).ConfigureAwait(false); } private static async Task WriteExceptionAsync(HttpContext context, Exception e) { if (e is UnauthorizedAccessException) context.Response.StatusCode = (int)HttpStatusCode.Unauthorized; else if (e is Exception) context.Response.StatusCode = (int)HttpStatusCode.BadRequest; context.Response.ContentType = "application/json"; var ro = new ResponseOutput(); ro.Successed = false; ro.Data = e; ro.Msg = "全局数据异常"; await context.Response.WriteAsync(JsonConvert.SerializeObject(ro)).ConfigureAwait(false); } } }