using Microsoft.AspNetCore.Mvc.Filters;
using Newtonsoft.Json;
using Mall.Common;
using Mall.Common.API;
using Mall.Common.Plugin;
using System.Net;
using System.Net.Http;

namespace Mall.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("拦截异常信息:" + context.Exception);
                }
                catch
                {

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

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