dotnet core webapi 实现 异常处理中间件

目录

第一步:创建异常处理中间件类(自定义响应格式)

[第二步:在 Program.cs 中使用中间件](#第二步:在 Program.cs 中使用中间件)

三、效果


第一步:创建异常处理中间件类(自定义响应格式)

复制代码
public static class ExceptionMiddlewareExtensions
{
    public static void ConfigureExceptionHandler(this IApplicationBuilder app, ILogger logger)
    {
        app.UseExceptionHandler(appError =>
        {
            appError.Run(async context =>
            {
                context.Response.StatusCode = StatusCodes.Status500InternalServerError;
                context.Response.ContentType = "application/json";

                var contextFeature = context.Features.Get<IExceptionHandlerFeature>();
                if (contextFeature != null)
                {
                    logger.LogError($"Something went wrong: {contextFeature.Error}");

                    await context.Response.WriteAsync(new
                    {
                        StatusCode = context.Response.StatusCode,
                        Message = "Internal Server Error. Please try again later.",
                        Detailed = contextFeature.Error.Message // 可以移除或改为只在开发模式返回
                    }.ToStringJson());
                }
            });
        });
    }

    private static string ToStringJson(this object obj)
    {
        return System.Text.Json.JsonSerializer.Serialize(obj);
    }
}

第二步:在 Program.cs 中使用中间件

复制代码
var builder = WebApplication.CreateBuilder(args);

// 日志支持
var logger = LoggerFactory.Create(config => config.AddConsole()).CreateLogger("GlobalExceptionHandler");

var app = builder.Build();

// 注册全局异常处理中间件
app.ConfigureExceptionHandler(logger);

// 其他中间件(如路由、授权等)
app.UseHttpsRedirection();
app.UseAuthorization();
app.MapControllers();

app.Run();

三、效果

当你的接口中出现未捕获的异常(例如空引用、除零等)时,将统一返回如下格式的响应:

复制代码
{
  "StatusCode": 500,
  "Message": "Internal Server Error. Please try again later.",
  "Detailed": "Object reference not set to an instance of an object."
}

你可以根据需要隐藏 Detailed 字段,或者根据环境自动判断是否返回详细信息(例如仅开发环境)。

相关推荐
安全系统学习2 天前
网络安全逆向分析之rust逆向技巧
前端·算法·安全·web安全·网络安全·中间件
NoneCoder2 天前
Redux 实践与中间件应用
前端·react.js·中间件·面试
淡水猫.2 天前
Next.js 中间件鉴权绕过漏洞 CVE-2025-29927
javascript·安全·web安全·中间件
vvilkim3 天前
ASP.NET Core 中间件深度解析:构建灵活高效的请求处理管道
后端·中间件·asp.net
厚衣服_33 天前
第5篇《中间件负载均衡与连接池管理机制设计》
运维·中间件·负载均衡
老K(郭云开)4 天前
allWebPlugin中间件VLC专用版之截图功能介绍
前端·javascript·chrome·中间件·edge
Java小后生4 天前
基于Java的OPCDA采集中间件
中间件·opcda
安全系统学习5 天前
内网横向之RDP缓存利用
前端·安全·web安全·网络安全·中间件
健康平安的活着5 天前
mysql数据库实现分库分表,读写分离中间件sharding-sphere
数据库·mysql·中间件
厚衣服_35 天前
第1篇:数据库中间件概述:架构演进、典型方案与应用场景
数据库·中间件·架构