48 lines
1.6 KiB
C#
48 lines
1.6 KiB
C#
using Microsoft.AspNetCore.Mvc;
|
|
using Microsoft.AspNetCore.Mvc.Filters;
|
|
using Microsoft.Extensions.Logging;
|
|
using System;
|
|
using System.Collections.Generic;
|
|
using System.Linq;
|
|
using System.Threading.Tasks;
|
|
|
|
namespace LangGuan.Middleware
|
|
{
|
|
/// <summary>
|
|
/// 异常处理中间件
|
|
/// </summary>
|
|
public class CustomerExceptionFilter : IAsyncExceptionFilter
|
|
{
|
|
/// <summary>
|
|
/// 日志
|
|
/// </summary>
|
|
public ILogger _logger;
|
|
/// <summary>
|
|
/// 构参
|
|
/// </summary>
|
|
/// <param name="loggerFactory"></param>
|
|
public CustomerExceptionFilter(ILoggerFactory loggerFactory)
|
|
{
|
|
_logger = loggerFactory.CreateLogger<CustomerExceptionFilter>();
|
|
}
|
|
/// <summary>
|
|
/// 重写
|
|
/// </summary>
|
|
/// <param name="context"></param>
|
|
/// <returns></returns>
|
|
public Task OnExceptionAsync(ExceptionContext context)
|
|
{
|
|
if (context.ExceptionHandled == false)
|
|
{
|
|
var json = new { cdoe = -1, msg = context.Exception.Message, data = context.Exception.Data };
|
|
context.HttpContext.Response.StatusCode = 400;
|
|
context.Result = new JsonResult(json);
|
|
}
|
|
_logger.LogError($"请求出现异常,地址:{context.HttpContext?.Request?.Path},请求方式:{context.HttpContext.Request.Method},异常信息:{context.Exception.Message}");
|
|
//记录异常已经处理
|
|
context.ExceptionHandled = true;
|
|
return Task.CompletedTask;
|
|
}
|
|
}
|
|
}
|