2020-04-10 18:15:11 +08:00
|
|
|
|
using System;
|
2020-04-13 08:35:54 +08:00
|
|
|
|
using FAuth.Models;
|
2020-04-10 18:15:11 +08:00
|
|
|
|
using Microsoft.AspNetCore.Http;
|
|
|
|
|
using Microsoft.AspNetCore.Mvc;
|
|
|
|
|
using Microsoft.AspNetCore.Mvc.Filters;
|
|
|
|
|
using Microsoft.Extensions.Logging;
|
|
|
|
|
|
2020-04-13 08:35:54 +08:00
|
|
|
|
namespace FAuth.Extensions
|
2020-04-10 18:15:11 +08:00
|
|
|
|
{
|
|
|
|
|
/// <summary>
|
|
|
|
|
/// Api控制器返回异常
|
|
|
|
|
/// </summary>
|
|
|
|
|
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method,AllowMultiple = true,Inherited = true)]
|
|
|
|
|
public class ApiExceptionFilterAttribute:ExceptionFilterAttribute
|
|
|
|
|
{
|
|
|
|
|
public ILogger Logger { get; set; }
|
|
|
|
|
|
|
|
|
|
public ApiExceptionFilterAttribute(ILogger<ApiExceptionFilterAttribute> logger) {
|
|
|
|
|
this.Logger = logger;
|
|
|
|
|
}
|
|
|
|
|
public override void OnException(ExceptionContext context) {
|
2020-04-12 16:06:23 +08:00
|
|
|
|
var id = Guid.NewGuid().ToString("N");
|
|
|
|
|
this.Logger.LogError(id + "|" + context.Exception.ToString());
|
2020-04-10 18:15:11 +08:00
|
|
|
|
var result = new ApiErrorResult {
|
|
|
|
|
Message = context.Exception.Message,
|
2020-04-12 16:06:23 +08:00
|
|
|
|
Id = id,
|
2020-04-10 18:15:11 +08:00
|
|
|
|
};
|
2020-05-06 15:57:09 +08:00
|
|
|
|
var sc =
|
|
|
|
|
context.Exception is ApiException ? StatusCodes.Status400BadRequest :
|
|
|
|
|
StatusCodes.Status500InternalServerError;
|
|
|
|
|
|
|
|
|
|
context.Result = new JsonResult(result) { StatusCode = sc };
|
2020-04-10 18:15:11 +08:00
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
}
|
|
|
|
|
}
|