using System;
using System.Text;
using DS.WMS.PrintApi.Model;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using NLog;
namespace DS.WMS.PrintApi
{
///
/// 全局异常错误日志
///
public class GlobalExceptionsFilter : IExceptionFilter
{
private readonly IHostingEnvironment _env;
private static readonly Logger Logger = LogManager.GetCurrentClassLogger();
public GlobalExceptionsFilter(IHostingEnvironment env)
{
_env = env;
}
public void OnException(ExceptionContext context)
{
var json = new JsonErrorResponse();
json.Message = context.Exception.Message; //错误信息
if (_env.IsDevelopment())
{
json.DevelopmentMessage = context.Exception.StackTrace; //堆栈信息
}
var result = PrintDataResult.Failed(json.Message);
var objectResult = new BadRequestObjectResult(result);
objectResult.StatusCode = (int?)StatusCodes.Status200OK;
context.Result = objectResult;
// context.Result = new InternalServerErrorObjectResult(json);
//MiniProfiler.Current.CustomTiming("Errors:", json.Message);
//记录异常到日志
StringBuilder exMsg = new StringBuilder();
exMsg.AppendLine($"【异常方法:】{context.HttpContext.Request.Path}");
exMsg.AppendLine($"【请求类型:】{context.HttpContext.Request.Method}");
exMsg.AppendLine($"【异常错误:】{context.Exception.Message}");
exMsg.AppendLine($"【堆栈跟踪:】{context.Exception.StackTrace}");
// logger.LogError(exMsg.ToString());
Logger.Log(NLog.LogLevel.Error, exMsg.ToString());
// Logger.Log(NLog.LogLevel.Info, "异常信息:" + JsonConvert.SerializeObject(context.Exception));
//采用log4net 进行错误日志记录
//_loggerHelper.Error(json.Message, WriteLog(json.Message, context.Exception));
//_hubContext.Clients.All.SendAsync("ReceiveUpdate", LogLock.GetLogData()).Wait();
}
///
/// 自定义返回格式
///
///
///
///
public string WriteLog(string throwMsg, Exception ex)
{
return string.Format("【自定义错误】:{0} \r\n【异常类型】:{1} \r\n【异常信息】:{2} \r\n【堆栈调用】:{3}", new object[]
{
throwMsg,
ex.GetType().Name, ex.Message, ex.StackTrace
});
}
}
///
///
///
public class InternalServerErrorObjectResult : ObjectResult
{
public InternalServerErrorObjectResult(object value) : base(value)
{
StatusCode = StatusCodes.Status500InternalServerError;
}
}
///
/// 返回错误信息
///
public class JsonErrorResponse
{
///
/// 生产环境的消息
///
public string Message { get; set; }
///
/// 开发环境的消息
///
public string DevelopmentMessage { get; set; }
}
}