using Microsoft.AspNetCore.Mvc.Filters;
using Newtonsoft.Json;
using Edu.Common;
using Edu.Common.API;
using Edu.Common.Plugin;

namespace Edu.WebApi.Filter
{
    /// <summary>
    /// Api异常过滤
    /// </summary>
    public class ApiExceptionFilterAttribute : ExceptionFilterAttribute
    {
        /// <summary>
        /// 异常处理拦截
        /// </summary>
        /// <param name="context"></param>
        public override void OnException(ExceptionContext context)
        {
            if (context.Exception.Message != "The operation was canceled." && !context.Exception.Message.Contains("已取消该操作"))
            {
                try
                {
                    LogHelper.WriteInfo("ApiExceptionFilter_1:" + context.Exception);
                }
                catch
                {

                }
            }
            //记录错误日志
            if (context.HttpContext.Items[GlobalKey.UserPostInfo] != null)
            {
                LogHelper.Write(context.Exception,$"ApiExceptionFilter_2：{Config.GetFilePath(context.HttpContext.Request.GetAbsoluteUri())},请求参数：{JsonConvert.SerializeObject(context.HttpContext.Items[GlobalKey.UserPostInfo].ToString())}");
            }
            else
            {
                LogHelper.Write(context.Exception,$"ApiExceptionFilter_3：{Config.GetFilePath(context.HttpContext.Request.GetAbsoluteUri())}");
            }

            var robj = new ApiResult()
            {
                Code = (int)ResultCode.AbnormalServer,
                Message = "服务器繁忙,请稍后再试",
                Data = null
            }; 
            context.Result = new Microsoft.AspNetCore.Mvc.JsonResult(robj);
        }
    }
}