惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

月光博客
月光博客
Stack Overflow Blog
Stack Overflow Blog
L
LangChain Blog
Jina AI
Jina AI
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
雷峰网
雷峰网
T
Tailwind CSS Blog
MongoDB | Blog
MongoDB | Blog
博客园 - 【当耐特】
博客园 - 聂微东
V
Visual Studio Blog
博客园_首页
Engineering at Meta
Engineering at Meta
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
The Cloudflare Blog
人人都是产品经理
人人都是产品经理
Apple Machine Learning Research
Apple Machine Learning Research
阮一峰的网络日志
阮一峰的网络日志
Microsoft Security Blog
Microsoft Security Blog
GbyAI
GbyAI
F
Fortinet All Blogs
C
Check Point Blog
罗磊的独立博客
H
Hackread – Cybersecurity News, Data Breaches, AI and More

博客园 - 试试手气

Web Worker 入门 若依Ruoyi分离版替换 MyBatis-Plus 若依前端菜单管理中路由地址、组件路径、权限字符的使用 Idea clone 项目推送到自有仓库 Spring Boot —— Spring Security Spring Boot —— 集成文档工具 Spring Boot —— Filter 过滤器 Spring Boot —— Cors 跨域 Spring Boot —— 集成 Druid Spring Boot —— 集成 MyBatis-Plus Spring Boot —— 集成 Springdoc Navicat 使用笔记 Datagrip连接SQLServer失败 Asp.net mvc 笔记 Asp.net Core 笔记 mybatis 笔记 SQLServer 笔记 SqlSugar 实践笔记 Asp.net Core 基于Cookie的身份认证
Asp.net Core 全局异常处理
试试手气 · 2023-03-23 · via 博客园 - 试试手气

中间件方式

  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 }));
        }
    }
}

引用

ASP.NET Core Web API通过中间件或UseExceptionHandler异常处理方法