shgx_tz_mom/ZR.Admin.WebApi/Middleware/GlobalExceptionMiddleware.cs

138 lines
5.1 KiB
C#
Raw Normal View History

2024-06-07 11:04:26 +08:00
using IPTools.Core;
using Microsoft.AspNetCore.Http.Features;
2021-08-23 16:57:25 +08:00
using NLog;
using System.Text.Encodings.Web;
using System.Text.Json;
2021-08-23 16:57:25 +08:00
using ZR.Admin.WebApi.Extensions;
using ZR.Model.System;
2021-09-16 19:35:17 +08:00
using ZR.Service.System.IService;
2021-08-23 16:57:25 +08:00
namespace ZR.Admin.WebApi.Middleware
{
/// <summary>
/// 全局异常处理中间件
2023-02-23 08:45:54 +08:00
/// 调用 app.UseMiddlewareGlobalExceptionMiddleware>();
2021-08-23 16:57:25 +08:00
/// </summary>
public class GlobalExceptionMiddleware
{
private readonly RequestDelegate next;
private readonly ISysOperLogService SysOperLogService;
static readonly Logger Logger = LogManager.GetCurrentClassLogger();
2021-08-23 16:57:25 +08:00
public GlobalExceptionMiddleware(RequestDelegate next, ISysOperLogService sysOperLog)
{
this.next = next;
this.SysOperLogService = sysOperLog;
}
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)
{
2022-03-06 14:26:05 +08:00
NLog.LogLevel logLevel = NLog.LogLevel.Info;
2021-08-23 16:57:25 +08:00
int code = (int)ResultCode.GLOBAL_ERROR;
string msg;
string error = string.Empty;
//自定义异常
if (ex is CustomException customException)
{
code = customException.Code;
msg = customException.Message;
error = customException.LogMsg;
}
else if (ex is ArgumentException)//参数异常
{
code = (int)ResultCode.PARAM_ERROR;
msg = ex.Message;
}
else
{
2023-04-25 11:59:19 +08:00
msg = "服务器好像出了点问题,请联系系统管理员...";
2021-08-23 16:57:25 +08:00
error = $"{ex.Message}";
2022-03-06 14:26:05 +08:00
logLevel = NLog.LogLevel.Error;
2021-08-23 16:57:25 +08:00
context.Response.StatusCode = 500;
}
var options = new JsonSerializerOptions
{
Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping,
PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
WriteIndented = true
};
2021-08-23 16:57:25 +08:00
ApiResult apiResult = new(code, msg);
string responseResult = JsonSerializer.Serialize(apiResult, options).ToLower();
2021-08-23 16:57:25 +08:00
string ip = HttpContextExtension.GetClientUserIp(context);
var ip_info = IpTool.Search(ip);
SysOperLog sysOperLog = new()
{
2022-09-01 21:54:53 +08:00
Status = 1,
OperIp = ip,
OperUrl = HttpContextExtension.GetRequestUrl(context),
RequestMethod = context.Request.Method,
JsonResult = responseResult,
ErrorMsg = string.IsNullOrEmpty(error) ? msg : error,
OperName = HttpContextExtension.GetName(context),
2022-09-01 21:54:53 +08:00
OperLocation = ip_info.Province + " " + ip_info.City,
OperTime = DateTime.Now
2021-08-23 16:57:25 +08:00
};
2022-05-10 13:27:11 +08:00
HttpContextExtension.GetRequestValue(context, sysOperLog);
var endpoint = GetEndpoint(context);
if (endpoint != null)
{
var logAttribute = endpoint.Metadata.GetMetadata<LogAttribute>();
if (logAttribute != null)
{
2023-04-20 21:47:55 +08:00
sysOperLog.BusinessType = (int)logAttribute.BusinessType;
2022-09-01 21:54:53 +08:00
sysOperLog.Title = logAttribute?.Title;
sysOperLog.OperParam = logAttribute.IsSaveRequestData ? sysOperLog.OperParam : "";
sysOperLog.JsonResult = logAttribute.IsSaveResponseData ? sysOperLog.JsonResult : "";
}
}
LogEventInfo ei = new(logLevel, "GlobalExceptionMiddleware", error)
{
Exception = ex,
Message = error
};
2021-08-23 16:57:25 +08:00
ei.Properties["status"] = 1;//走正常返回都是通过走GlobalExceptionFilter不通过
ei.Properties["jsonResult"] = responseResult;
2022-09-01 21:54:53 +08:00
ei.Properties["requestParam"] = sysOperLog.OperParam;
ei.Properties["user"] = sysOperLog.OperName;
2021-08-23 16:57:25 +08:00
Logger.Log(ei);
context.Response.ContentType = "text/json;charset=utf-8";
await context.Response.WriteAsync(responseResult, System.Text.Encoding.UTF8);
2024-06-07 11:04:26 +08:00
string errorMsg = $"> 操作人:{sysOperLog.OperName}" +
$"\n> 操作地区:{sysOperLog.OperIp}({sysOperLog.OperLocation})" +
$"\n> 操作模块:{sysOperLog.Title}" +
$"\n> 操作地址:{sysOperLog.OperUrl}" +
$"\n> 错误信息:{msg}\n\n> {error}";
2024-06-07 11:04:26 +08:00
WxNoticeHelper.SendMsg("系统出错", errorMsg, "", WxNoticeHelper.MsgType.markdown);
2021-08-23 16:57:25 +08:00
SysOperLogService.InsertOperlog(sysOperLog);
}
public static Endpoint GetEndpoint(HttpContext context)
{
if (context == null)
{
throw new ArgumentNullException(nameof(context));
}
return context.Features.Get<IEndpointFeature>()?.Endpoint;
}
2021-08-23 16:57:25 +08:00
}
}