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 字段,或者根据环境自动判断是否返回详细信息(例如仅开发环境)。

相关推荐
车载中间件通信10 小时前
[TC8测试]TCP_FLAGS_PROCESSING_06
数据库·网络协议·tcp/ip·中间件·tc8
kingx31 天前
网络安全事件应急响应:X集团 WebServer 入侵溯源与处置
中间件·web·应急响应·取证·恶意样本
特立独行的猫a2 天前
ROS 2 主流DDS中间件入门:Cyclone DDS 与 Fast DDS 完全指南
中间件·ros2·dds·fast dds·cyclone dds
小易老师AI实战2 天前
用中间件把任务规划嵌进智能体循环
中间件·状态管理·智能体·工具调用·langgraph·任务规划
绿蕉3 天前
从硬件内卷到“中间件荒“——仿真工具、开发接口、开源生态
中间件·机器人
小易老师AI实战3 天前
LangGraph Agent 任务规划中间件:TodoListMiddleware 原理解析
中间件·agent·langgraph·任务规划·大模型智能体
eleven_4u4 天前
QPS如何计算,如何部署架构
java·linux·运维·jvm·中间件
喵了几个咪5 天前
GoWind ShortPlay 拆解:Ent privacy/viewer 多租户隔离——从中间件到 SQL 的零信任链
sql·中间件·信任链
ctlover6 天前
langchain 中间件
中间件·langchain·1024程序员节
宝贝儿好9 天前
【LLM】第十一章:Agent中间件2:ModelCallLimitMiddleware
中间件