using Microsoft.AspNetCore.Http; using Newtonsoft.Json; using System; using System.Net; using System.Threading.Tasks; using Wood.Entity; using Wood.EventBus; using Wood.EventBus.Events; using Wood.Util; namespace Wood.Admin.WebApi.Middleware { /// /// 全局异常中间件 /// public class GlobalExceptionMiddleware { private readonly RequestDelegate _next; private readonly IEventBus _eventBus; /// /// 全局异常中间件 /// /// /// public GlobalExceptionMiddleware(RequestDelegate next, IEventBus eventBus) { _next = next; _eventBus = eventBus; } /// /// /// /// /// public async Task Invoke(HttpContext context /* other dependencies */) { try { await _next(context); } catch (Exception ex) { await HandleExceptionAsync(context, ex); } } /// /// /// /// /// /// private Task HandleExceptionAsync(HttpContext context, Exception exception) { var user = GlobalContext.UserInfo; var entity = new Entity.SystemManage.LogExceptionEntity { UserName = user?.UserName, RealName = user?.RealName, HttpMethod = context.Request.Method.ToUpper(), Browser = NetHelper.Browser, Os = NetHelper.GetOSVersion(), Exception = exception.GetFullExceptionMessage(), ExceptionStackTrace = exception.StackTrace, Elapsed = 0, LogDateTime = DateTime.Now, IpAddress = NetHelper.Ip, Source = this.GetType().Name, }; entity.RequestUrl = context.Request.Path; entity.RequestParam = context.Request.QueryString.Value; _eventBus.Publish(new LogExceptionEvent(entity)); var code = HttpStatusCode.OK; context.Response.ContentType = "application/json"; context.Response.StatusCode = (int)code; return context.Response.WriteAsync(JsonConvert.SerializeObject(TData.Error())); } } }