小修改api异常处理筛选器

This commit is contained in:
falcon 2022-10-08 14:02:49 +08:00
parent dfc4e91cd6
commit da07c27221

View File

@ -6,6 +6,9 @@ using System.Text;
namespace Falcon.SugarApi.ApiDefinistions namespace Falcon.SugarApi.ApiDefinistions
{ {
/// <summary>
/// 异常处理筛选器
/// </summary>
public class HttpResponseExceptionFilter : IActionFilter, IOrderedFilter public class HttpResponseExceptionFilter : IActionFilter, IOrderedFilter
{ {
/// <summary> /// <summary>
@ -13,32 +16,36 @@ namespace Falcon.SugarApi.ApiDefinistions
/// </summary> /// </summary>
public ILogger Logger { get; set; } public ILogger Logger { get; set; }
public HttpResponseExceptionFilter(ILogger<HttpResponseExceptionFilter> logger) /// <summary>
{ /// api异常状态码
/// </summary>
public int StatusCode { get; set; } = 400;
/// <inheritdoc/>
public HttpResponseExceptionFilter(ILogger<HttpResponseExceptionFilter> logger) {
this.Logger = logger; this.Logger = logger;
} }
/// <inheritdoc/>
public int Order { get; } = int.MaxValue - 10; public int Order { get; } = int.MaxValue - 10;
/// <inheritdoc/>
public void OnActionExecuting(ActionExecutingContext context) { } public void OnActionExecuting(ActionExecutingContext context) { }
public void OnActionExecuted(ActionExecutedContext context) /// <inheritdoc/>
{ public void OnActionExecuted(ActionExecutedContext context) {
if (context.Exception == null || context.ExceptionHandled) if (context.Exception == null || context.ExceptionHandled) {
{
return; return;
} }
var exception = context.Exception; var exception = context.Exception;
var now = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"); var now = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
var model = new ExceptionModel var model = new ExceptionModel {
{
Id = Guid.NewGuid().ToString(), Id = Guid.NewGuid().ToString(),
CreateDateTime = now, CreateDateTime = now,
Message = exception.Message, Message = exception.Message,
}; };
if (exception is ApiException) if (exception is ApiException) {
{ context.Result = new ObjectResult(model) { StatusCode = this.StatusCode, };
context.Result = new ObjectResult(model) { StatusCode = 400, };
context.ExceptionHandled = true; context.ExceptionHandled = true;
} }
var logmsg = new StringBuilder(); var logmsg = new StringBuilder();