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

推荐订阅源

雷峰网
雷峰网
IT之家
IT之家
Last Week in AI
Last Week in AI
J
Java Code Geeks
L
LangChain Blog
Recent Announcements
Recent Announcements
Martin Fowler
Martin Fowler
H
Hackread – Cybersecurity News, Data Breaches, AI and More
Google DeepMind News
Google DeepMind News
博客园 - Franky
博客园 - 司徒正美
月光博客
月光博客
博客园 - 叶小钗
Vercel News
Vercel News
腾讯CDC
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
小众软件
小众软件
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
GbyAI
GbyAI
B
Blog RSS Feed
人人都是产品经理
人人都是产品经理
H
Help Net Security
G
Google Developers Blog
D
DataBreaches.Net

博客园 - 试试手气

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