z8018
2 天以前 d8dc91f9c1fece5711e38edd1b1274cb9e579015
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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
using Microsoft.AspNetCore.Http;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.DirectoryServices.Protocols;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
 
namespace WIDESEA_Core.Middlewares
{
    public class ExceptionHandlerMiddleware
    {
        private readonly RequestDelegate _next;
 
        public ExceptionHandlerMiddleware(RequestDelegate next)
        {
            _next = next;
        }
 
        /// <summary>
        /// 处理HTTP请求并捕获异常
        /// </summary>
        /// <param name="context">HTTP上下文</param>
        /// <returns>表示异步操作的任务</returns>
        /// <remarks>
        /// 当请求处理过程中发生异常时,会调用HandleExceptionAsync方法进行处理
        /// </remarks>
        public async Task Invoke(HttpContext context)
        {
            try
            {
                await _next(context);
            }
            catch (Exception ex)
            {
                await HandleExceptionAsync(context, ex);
            }
        }
 
        /// <summary>
        /// 异步处理异常并写入响应
        /// </summary>
        /// <param name="context">HTTP上下文</param>
        /// <param name="e">待处理的异常对象</param>
        /// <returns>表示异步操作的任务</returns>
        private async Task HandleExceptionAsync(HttpContext context, Exception e)
        {
            if (e == null) return;
 
            await WriteExceptionAsync(context, e).ConfigureAwait(false);
        }
 
        /// <summary>
        /// 异步将异常信息写入HTTP响应
        /// </summary>
        /// <param name="context">HTTP上下文对象</param>
        /// <param name="e">发生的异常</param>
        /// <remarks>
        /// 根据异常类型设置对应的HTTP状态码:
        /// - UnauthorizedAccessException: 返回401未授权状态码
        /// - 其他异常: 返回500内部服务器错误状态码
        /// 响应内容为JSON格式的错误信息
        /// </remarks>
        private static async Task WriteExceptionAsync(HttpContext context, Exception e)
        {
            var message = e.Message;
            switch (e)
            {
                case UnauthorizedAccessException:
                    context.Response.StatusCode = (int)HttpStatusCode.Unauthorized;
                    break;
                default:
                    context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
                    break;
            }
            context.Response.ContentType = "application/json";
            await context.Response
                .WriteAsync(JsonConvert.SerializeObject(WebResponseContent.Instance.Error(message)))
                .ConfigureAwait(false);
        }
    }
}