using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Performance.Subsidy.Api.Filters
{
    public class ExceptionsFilter : IAsyncExceptionFilter
    {
        private readonly ILogger<ExceptionsFilter> _logger;

        public ExceptionsFilter(ILogger<ExceptionsFilter> logger)
        {
            this._logger = logger;
        }

        public Task OnExceptionAsync(ExceptionContext context)
        {
            
            if(context.Exception is Exception)
            {
                _logger.LogError($"接口异常:{context.Exception.ToString()}");
                var response = new ApiResponse(Status.Error, "接口内部异常", context.Exception.Message);
                context.Result = new ObjectResult(response);
                _logger.LogError("接口内部异常" + JsonConvert.SerializeObject(response, Formatting.None));
            }
            return Task.CompletedTask;
        }
    }
}
