You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

81 lines
2.5 KiB

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
{
/// <summary>
/// 全局异常中间件
/// </summary>
public class GlobalExceptionMiddleware
{
private readonly RequestDelegate _next;
private readonly IEventBus _eventBus;
/// <summary>
/// 全局异常中间件
/// </summary>
/// <param name="next"></param>
/// <param name="eventBus"></param>
public GlobalExceptionMiddleware(RequestDelegate next, IEventBus eventBus)
{
_next = next;
_eventBus = eventBus;
}
/// <summary>
///
/// </summary>
/// <param name="context"></param>
/// <returns></returns>
public async Task Invoke(HttpContext context /* other dependencies */)
{
try
{
await _next(context);
}
catch (Exception ex)
{
await HandleExceptionAsync(context, ex);
}
}
/// <summary>
///
/// </summary>
/// <param name="context"></param>
/// <param name="exception"></param>
/// <returns></returns>
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()));
}
}
}