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
{
    /// <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) {
            var id = Guid.NewGuid().ToString("N");
            this.Logger.LogError(id + "|" + context.Exception.ToString());
            var result = new ApiErrorResult {
                Message = context.Exception.Message,
                Id = id,
            };
            var sc =
                context.Exception is ApiException ? StatusCodes.Status400BadRequest :
                StatusCodes.Status500InternalServerError;

            context.Result = new JsonResult(result) { StatusCode = sc };
        }

    }
}
