63 lines
2.0 KiB
C#
63 lines
2.0 KiB
C#
using Microsoft.AspNetCore.Mvc;
|
|
using Microsoft.AspNetCore.Mvc.Filters;
|
|
using Microsoft.Extensions.Logging;
|
|
using System;
|
|
using System.Text;
|
|
|
|
namespace Falcon.SugarApi.ApiDefinistions
|
|
{
|
|
/// <summary>
|
|
/// 异常处理筛选器
|
|
/// </summary>
|
|
public class HttpResponseExceptionFilter : IActionFilter, IOrderedFilter
|
|
{
|
|
/// <summary>
|
|
/// 日志记录器
|
|
/// </summary>
|
|
public ILogger Logger { get; set; }
|
|
|
|
/// <summary>
|
|
/// api异常状态码
|
|
/// </summary>
|
|
public int StatusCode { get; set; } = 400;
|
|
|
|
/// <inheritdoc/>
|
|
public HttpResponseExceptionFilter(ILogger<HttpResponseExceptionFilter> logger) {
|
|
this.Logger = logger;
|
|
}
|
|
|
|
/// <inheritdoc/>
|
|
public int Order { get; } = int.MaxValue - 10;
|
|
|
|
/// <inheritdoc/>
|
|
public void OnActionExecuting(ActionExecutingContext context) { }
|
|
|
|
/// <inheritdoc/>
|
|
public void OnActionExecuted(ActionExecutedContext context) {
|
|
if (context.Exception == null || context.ExceptionHandled) {
|
|
return;
|
|
}
|
|
var exception = context.Exception;
|
|
var now = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
|
|
var model = new ExceptionModel {
|
|
Id = Guid.NewGuid().ToString(),
|
|
CreateDateTime = now,
|
|
Message = exception.Message,
|
|
};
|
|
if (exception is ApiException ae) {
|
|
if (ae.Id.HasValue) {
|
|
model.Id = ae.Id.Value.ToString();
|
|
}
|
|
context.Result = new ObjectResult(model) { StatusCode = this.StatusCode, };
|
|
context.ExceptionHandled = true;
|
|
}
|
|
var logmsg = new StringBuilder();
|
|
logmsg.AppendLine($"异常编号:{model.Id}");
|
|
logmsg.AppendLine($"错误信息:{model.Message}");
|
|
logmsg.AppendLine($"详细信息:");
|
|
logmsg.AppendLine($"{exception}");
|
|
this.Logger.LogError(logmsg.ToString());
|
|
}
|
|
}
|
|
}
|