Asp.net Core 全局异常处理

发布时间 2023-03-23 17:19:17作者: Cinlap Soft

中间件方式

  1. 建立中间件处理类
  2. Startup.cs 中注册
  3. 任何Controller中的Action抛出异常均可被捕捉

在项目根目录下自建目录Middleware
image

新建中间件类ErrorHandlerMiddleware

using Newtonsoft.Json;
using System.Net;
using Uap.Exceptions;

namespace Uap.Middleware
{
    /// <summary>
    /// 全局错误处理中间件
    /// </summary>
    public class ErrorHandlerMiddleware
    {
        private readonly RequestDelegate next;

        public ErrorHandlerMiddleware(RequestDelegate next)
        {
            this.next = next;
        }

        public async Task Invoke(HttpContext context)
        {
            try
            {
                await next(context);
            }
            catch (Exception ex)
            {
                await HandleExceptionAsync(context, ex);
            }
        }

        private static Task HandleExceptionAsync(HttpContext context, Exception ex)
        {
            var code = 0;
            var message = "Unknown error";

            // BadHttpRequestException,请求类错误
            // ServiceException,自定义的后端处理类错误

            if (ex is BadHttpRequestException)
            {
                code = ((BadHttpRequestException)ex).StatusCode;
                message = ex.Message;
            }
            else if (ex is ServiceException)
            {
                code = (int)((ServiceException)ex).StatusCode;
                message = ex.Message;
            }
            else
            {
                code = (int)HttpStatusCode.InternalServerError;
                message = "Internal server error";
            }

            context.Response.ContentType = "application/json";
            context.Response.StatusCode = code;
            return context.Response.WriteAsync(JsonConvert.SerializeObject(new { message = message }));
        }
    }
}