【优化】调整全局异常处理器及过滤器异常日志存储名称问题,日志记录更加详细直观,同时修改类命名。

This commit is contained in:
大灰灰
2022-10-14 00:31:57 +08:00
parent f723defa85
commit 5351657cad
5 changed files with 10 additions and 10 deletions

View File

@@ -0,0 +1,75 @@
/***********************************************************************
* Project: CoreCms.Net *
* Web: https://CoreCms.Net *
* ProjectName: 核心内容管理系统 *
* Author: 大灰灰 *
* Email: JianWeie@163.com *
* Versions: 1.0 *
* CreateTime: 2020-02-05 19:08:19
* NameSpace: CoreCms.Net.Framework.Middlewares
* FileName: ExceptionHandlerMidd
* ClassDescription:
***********************************************************************/
using System;
using System.Net;
using System.Threading.Tasks;
using CoreCms.Net.Loging;
using CoreCms.Net.Model.ViewModels.UI;
using Microsoft.AspNetCore.Http;
using Newtonsoft.Json;
using NLog;
namespace CoreCms.Net.Middlewares;
/// <summary>
/// 异常错误统一返回记录
/// </summary>
public class ExceptionHandlerMiddlewareForClent
{
private readonly RequestDelegate _next;
public ExceptionHandlerMiddlewareForClent(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;
NLogUtil.WriteAll(LogLevel.Error, LogType.ApiRequest, "全局捕获异常", ex.Message, ex);
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 != null)
context.Response.StatusCode = (int)HttpStatusCode.BadRequest;
context.Response.ContentType = "application/json";
var jm = new WebApiCallBack();
jm.status = false;
jm.code = 500;
jm.data = e;
jm.msg = "全局数据异常";
await context.Response.WriteAsync(JsonConvert.SerializeObject(jm)).ConfigureAwait(false);
}
}