刘磊
2025-06-09 dabbcafc629ef87d11ba55ef8cc1cdc776c047d8
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
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;
        }
 
        public async Task Invoke(HttpContext context)
        {
            try
            {
                await _next(context);
            }
            catch (Exception ex)
            {
                await HandleExceptionAsync(context, ex);
            }
        }
 
        private async Task HandleExceptionAsync(HttpContext context, Exception e)
        {
            if (e == null) return;
 
            await WriteExceptionAsync(context, e).ConfigureAwait(false);
        }
 
        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);
        }
    }
}