68 lines
2.6 KiB
C#
68 lines
2.6 KiB
C#
using Furion.DependencyInjection;
|
|
using Furion.FriendlyException;
|
|
using Microsoft.AspNetCore.Diagnostics;
|
|
using Microsoft.AspNetCore.Http;
|
|
using Microsoft.AspNetCore.Mvc;
|
|
using Microsoft.AspNetCore.Mvc.Filters;
|
|
using Nirvana.Common.ApiBase;
|
|
using System;
|
|
using System.Collections.Generic;
|
|
using System.IO;
|
|
using System.Linq;
|
|
using System.Text;
|
|
using System.Threading.Tasks;
|
|
|
|
namespace YBDevice.Core
|
|
{
|
|
/// <summary>
|
|
/// 全局异常处理
|
|
/// </summary>
|
|
public class LogExceptionHandler : IGlobalExceptionHandler, ISingleton
|
|
{
|
|
private readonly ILoggerService _loggerService;
|
|
|
|
public LogExceptionHandler(ILoggerService loggerService)
|
|
{
|
|
_loggerService = loggerService;
|
|
}
|
|
public async Task OnExceptionAsync(ExceptionContext context)
|
|
{
|
|
// 写日志
|
|
if (context != null)
|
|
{
|
|
var ex = context.HttpContext.Features.Get<IExceptionHandlerFeature>();
|
|
//如果是用户取消的异常,则不必记录到日志
|
|
if (context.HttpContext.RequestAborted.IsCancellationRequested && (ex is TaskCanceledException || ex is OperationCanceledException))
|
|
{
|
|
context.HttpContext.Response.StatusCode = 200;
|
|
var result = new ResultInfo { code = ResultState.SYSTEMERROR, message = ex?.Error?.Message ?? "操作已取消" };
|
|
var contentresult = new JsonResult(result);
|
|
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 result = new ResultInfo { code = ResultState.SYSTEMERROR, message = exs?.Message ?? "系统异常" };
|
|
var contentresult = new JsonResult(result);
|
|
context.Result = contentresult;
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|