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

推荐订阅源

博客园_首页
博客园 - 【当耐特】
博客园 - 叶小钗
阮一峰的网络日志
阮一峰的网络日志
WordPress大学
WordPress大学
D
Docker
T
The Blog of Author Tim Ferriss
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
Microsoft Azure Blog
Microsoft Azure Blog
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
月光博客
月光博客
M
MIT News - Artificial intelligence
H
Hackread – Cybersecurity News, Data Breaches, AI and More
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
云风的 BLOG
云风的 BLOG
F
Fortinet All Blogs
罗磊的独立博客
小众软件
小众软件
A
About on SuperTechFans
MyScale Blog
MyScale Blog
D
DataBreaches.Net
The GitHub Blog
The GitHub Blog
C
Check Point Blog
L
LangChain Blog

博客园 - 试试手气

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异常处理方法