Waste/Waste.Application/LogExceptionHandler.cs

72 lines
2.7 KiB
C#
Raw Permalink Normal View History

2021-04-30 14:52:42 +08:00
using Furion.DependencyInjection;
using Furion.FriendlyException;
2021-05-27 16:58:40 +08:00
using Microsoft.AspNetCore.Diagnostics;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
2021-04-30 14:52:42 +08:00
using Microsoft.AspNetCore.Mvc.Filters;
2021-05-27 16:58:40 +08:00
using Nirvana.Common;
using Nirvana.Common.ApiBase;
2021-04-30 14:52:42 +08:00
using System;
using System.Collections.Generic;
2021-05-27 16:58:40 +08:00
using System.IO;
2021-04-30 14:52:42 +08:00
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Waste.Application
{
public class LogExceptionHandler : IGlobalExceptionHandler, ISingleton
{
2021-05-27 16:58:40 +08:00
private readonly ILoggerService _loggerService;
public LogExceptionHandler(ILoggerService loggerService)
{
_loggerService = loggerService;
}
2021-04-30 14:52:42 +08:00
/// <summary>
/// 全局异常处理提供器
/// </summary>
/// <param name="context"></param>
/// <returns></returns>
2021-05-27 16:58:40 +08:00
public async Task OnExceptionAsync(ExceptionContext context)
2021-04-30 14:52:42 +08:00
{
// 写日志
2021-05-27 16:58:40 +08:00
if (context != null)
{
var ex = context.HttpContext.Features.Get<IExceptionHandlerFeature>();
//如果是用户取消的异常,则不必记录到日志
if (context.HttpContext.RequestAborted.IsCancellationRequested && (ex is TaskCanceledException || ex is OperationCanceledException))
{
Console.WriteLine("用户取消了操作");
context.HttpContext.Response.StatusCode = 200;
var contentresult = new ContentResult();
contentresult.Content = "操作已取消";
context.Result = contentresult;
}
else
{
var request = context.HttpContext.Request;
var action = request.Path.Value;
var query_string = request.QueryString.Value;
if (request.Method == "POST" && request.ContentLength > 0)
{
request.EnableBuffering();
request.Body.Position = 0;
using (var sr = new StreamReader(request.Body))
{
query_string = await sr.ReadToEndAsync();
}
}
//记录日志
var exs = context.Exception;
_loggerService.AddErrorLogger(exs, query_string, action);
context.HttpContext.Response.StatusCode = 200;
var contentresult = new ContentResult();
contentresult.Content= "系统异常";
context.Result = contentresult;
}
}
2021-04-30 14:52:42 +08:00
}
}
}