.net6webapi捕获全局异常

using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Sino.Intelligence.DataAccess.IServiceAccess.ILogs;
using Sino.Intelligence.DataAccess.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;

namespace Sino.Intelligence.DataAccess.CustomMiddleware
{
    public class ExceptionHandlingMiddleware
    {
        private readonly RequestDelegate _next;  // 用来处理上下文请求  
        //private readonly ILogger<ExceptionHandlingMiddleware> _logger;
        private readonly ILogUtility _logUtility;
        public ExceptionHandlingMiddleware(RequestDelegate next, ILogUtility logUtility)
        {
            _next = next;
            _logUtility = logUtility;
        }

        public async Task InvokeAsync(HttpContext httpContext)
        {
            try
            {
                await _next(httpContext); //要么在中间件中处理,要么被传递到下一个中间件中去
            }
            catch (Exception ex)
            {
                await HandleExceptionAsync(httpContext, ex); // 捕获异常了 在HandleExceptionAsync中处理
            }
        }
        private async Task HandleExceptionAsync(HttpContext context, Exception exception)
        {
            context.Response.ContentType = "application/json";  // 返回json 类型
            var response = context.Response;

            var errorResponse = new ErrorResponse();
            

            // 自定义的异常错误信息类型
            switch (exception)
            {
                case ApplicationException ex:
                    if (ex.Message.Contains("Invalid token"))
                    {
                        response.StatusCode = (int)HttpStatusCode.Forbidden;
                        errorResponse.SetErrorMsg(ex.Message);
                        break;
                    }
                    response.StatusCode = (int)HttpStatusCode.BadRequest;
                    errorResponse.SetErrorMsg(ex.Message);
                    break;

                case KeyNotFoundException ex:
                    response.StatusCode = (int)HttpStatusCode.NotFound;
                    errorResponse.SetErrorMsg(ex.Message);
                    break;

                default:
                    response.StatusCode = (int)HttpStatusCode.InternalServerError;
                    //errorResponse.Message = "Internal Server errors. Check Logs!";
                    errorResponse.SetErrorMsg(exception.Message);
                    break;
            }

            var result = JsonConvert.SerializeObject(errorResponse);
            _logUtility.Error(typeof(ExceptionHandlingMiddleware).Name, "HandleExceptionAsync", result, exception);
            await context.Response.WriteAsync(result);
        }
    }
}

异常出口返回结构体

internal class ErrorResponse
    {
        public int Flag { get; set; }

        public int ErrorCode { get; set; }

        public string Message { get; set; }

        public bool IsOk => Flag == 1;

        public bool HasError => Flag == 0;

        public bool IsWaiting => Flag == 2;

        public ErrorResponse()
        {
            Flag = 0;
            ErrorCode = 0;
        }

        public void SetErrorMsg(string msg, int code = 0)
        {
            Message = msg;
            Flag = 0;
            ErrorCode = code;
        }

    }

最后一步注入中间件

app.UseMiddleware<ExceptionHandlingMiddleware>();

 

posted on 2023-09-13 10:02  白码一号  阅读(289)  评论(0编辑  收藏  举报