chengsc
2025-02-10 1dfd1aeeeefe6d6b379b15733dbdd784da1ce3db
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using Utility.Entity;
 
namespace Utility
{
    public class CustomerExceptionFilter : IAsyncExceptionFilter
    {
        /// <summary>
        /// 重写OnExceptionAsync方法,定义自己的处理逻辑
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        private readonly ILogger<CustomerExceptionFilter> _logger;
        public CustomerExceptionFilter(ILogger<CustomerExceptionFilter> logger)
        {
            _logger = logger;
        }
        public Task OnExceptionAsync(ExceptionContext context)
        {
            // 如果异常没有被处理则进行处理
            if (context.ExceptionHandled == false)
            {
                //var result = "系统异常,请联系管理员";
                //if (context.Exception is AppFriendlyException)
                var result = context.Exception.Message;
                var apiResponse = new ApiResponse<object>(
                        code: (int)ResponseEnum.Fail,
                        message: result,
                        data: result
                    );
                _logger.LogError(context.Exception, context.Exception.Message);
                context.Result = new ContentResult
                {
                    // 返回状态码设置为200,表示成功
                    StatusCode = StatusCodes.Status200OK,
                    // 设置返回格式
                    ContentType = "application/json;charset=utf-8",
                    Content = JsonConvert.SerializeObject(apiResponse)
                };
            }
            // 设置为true,表示异常已经被处理了
            context.ExceptionHandled = true;
            return Task.CompletedTask;
        }
    }
}