WYB
2021-03-22 91b8cdad021ab052e4991f3d41834a6f0ddc36b8
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 JiepeiWMS.AuthHelper.Policys;
using Microsoft.AspNetCore.Http;
using Newtonsoft.Json;
using System;
using System.Net;
using System.Threading.Tasks;
 
namespace JiepeiWMS.Middlewares
{
    public class ExceptionHandlerMidd
    {
        private readonly RequestDelegate _next;
        private static readonly log4net.ILog log =
        log4net.LogManager.GetLogger(typeof(ExceptionHandlerMidd));
 
        public ExceptionHandlerMidd(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;
 
            log.Error(e.GetBaseException().ToString());
 
            await WriteExceptionAsync(context, e).ConfigureAwait(false);
        }
 
        private static async Task WriteExceptionAsync(HttpContext context, Exception e)
        {
            if (e is UnauthorizedAccessException)
                context.Response.StatusCode = (int)HttpStatusCode.Unauthorized;
            else if (e is Exception)
                context.Response.StatusCode = (int)HttpStatusCode.BadRequest;
 
            context.Response.ContentType = "application/json";
 
            await context.Response.WriteAsync(JsonConvert.SerializeObject((new ApiResponse(StatusCode.CODE500, e.Message)).MessageModel)).ConfigureAwait(false);
        }
    }
}