using Microsoft.AspNetCore.Diagnostics;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc.Filters;
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.AspNetCore.Mvc;

namespace XYY.Core.Standard.Data.Infrastructure
{
    public class ApiExceptionAcitonFilterAttribute : Attribute, IExceptionFilter
    {
        public async void OnException(ExceptionContext context)
        {
            string errorMessage = context.Exception.Message;
            if (errorMessage.Contains("--->"))
            {
                errorMessage = errorMessage.Substring(errorMessage.IndexOf("--->") + 4);
            }
            string json = Newtonsoft.Json.JsonConvert.SerializeObject(new Mvc.ApiJsonModel
            {
                code = System.Net.HttpStatusCode.OK,
                data = null,
                success = false,
                message = "操作失败！" + errorMessage
            });
            if (context.ExceptionHandled == false)
            {
                string msg = json;
                context.Result = new ContentResult
                {
                    Content = msg,
                    StatusCode = StatusCodes.Status500InternalServerError,
                    ContentType = "application/json; charset=utf-8"
                };
                Console.WriteLine(msg);
            }
        }
    }
}
