移动系统liao
2024-04-26 7ab5760a2657ef9fdae3ab919a474075315c103c
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
/***********************************************************************
 *            Project: baifenBinfa.Net                                     *
 *                Web: https://baifenBinfa.com                             *
 *        ProjectName: 百分兵法管理系统                               *
 *             Author:                                        *
 *              Email:                               *
 *           Versions: 1.0                                             *
 *         CreateTime: 2020-02-05 19:08:19
 *          NameSpace: CoreCms.Net.Framework.Middlewares
 *           FileName: ExceptionHandlerMidd
 *   ClassDescription: 
 ***********************************************************************/
 
 
using System;
using System.Net;
using System.Threading.Tasks;
using CoreCms.Net.Loging;
using CoreCms.Net.Model.ViewModels.UI;
using Microsoft.AspNetCore.Http;
using Newtonsoft.Json;
using NLog;
 
namespace CoreCms.Net.Middlewares;
 
/// <summary>
///     异常错误统一返回记录
/// </summary>
public class ExceptionHandlerMiddlewareForAdmin
{
    private readonly RequestDelegate _next;
 
    public ExceptionHandlerMiddlewareForAdmin(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 ex)
    {
        if (ex == null) return;
        NLogUtil.WriteAll(LogLevel.Error, LogType.Web, "全局捕获异常", ex.Message, ex);
        await WriteExceptionAsync(context, ex).ConfigureAwait(false);
    }
 
    private static async Task WriteExceptionAsync(HttpContext context, Exception e)
    {
        if (e is UnauthorizedAccessException) context.Response.StatusCode = (int)HttpStatusCode.Unauthorized;
        else if (e != null) context.Response.StatusCode = (int)HttpStatusCode.BadRequest;
 
        context.Response.ContentType = "application/json";
        var jm = new AdminUiCallBack();
        jm.code = 500;
        jm.data = e;
        jm.msg = "全局捕获异常";
        await context.Response.WriteAsync(JsonConvert.SerializeObject(jm)).ConfigureAwait(false);
    }
}