using HuanMeng.DotNetCore.Base;

using Microsoft.AspNetCore.Mvc;

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CloudGaming.Code.Filter
{
    /// <summary>
    /// 异常过滤器
    /// </summary>
    public class CustomExceptionFilter : IExceptionFilter
    {
        public void OnException(ExceptionContext context)
        {
            var sw = Stopwatch.StartNew();
            // 检查异常是否是特定的异常类型
            if (context.Exception is MessageBox message)
            {
                var obj = message.ToBaseResponse();// new BaseResponse<object>(message.Code, message.Message, message.Data);
                //// 处理特定异常：记录日志、设置响应结果等
                //Console.WriteLine($"Custom exception caught: {message.Message}");

                // 设置自定义的响应结果
                context.Result = new JsonResult(obj)
                {
                    StatusCode = StatusCodes.Status200OK // 或者其他合适的HTTP状态码
                };

                // 标记异常已经被处理
                context.ExceptionHandled = true;
            }
            sw.Stop();
            context.HttpContext.Response.Headers.TryAdd("X-Request-Duration-CustomExceptionFilter", sw.Elapsed.TotalMilliseconds.ToString());
        }
    }
}
