using System;
using FAuth.Models;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.Extensions.Logging;
namespace FAuth.Extensions
{
///
/// Api控制器返回异常
///
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method,AllowMultiple = true,Inherited = true)]
public class ApiExceptionFilterAttribute:ExceptionFilterAttribute
{
public ILogger Logger { get; set; }
public ApiExceptionFilterAttribute(ILogger logger) {
this.Logger = logger;
}
public override void OnException(ExceptionContext context) {
var id = Guid.NewGuid().ToString("N");
this.Logger.LogError(id + "|" + context.Exception.ToString());
var result = new ApiErrorResult {
Message = context.Exception.Message,
Id = id,
};
context.Result = new JsonResult(result) { StatusCode = StatusCodes.Status500InternalServerError };
}
}
}