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

相关推荐
fantasy5_51 天前
从零手写线程池:把多线程、锁、同步、日志讲透
开发语言·c++·中间件
heimeiyingwang1 天前
【架构实战】海量数据存储:分库分表中间件实战
中间件·架构
别抢我的锅包肉1 天前
【FastAPI】 依赖注入 + 中间件详解
中间件·fastapi
敢敢のwings1 天前
ROS2通信中间件深度解析:从DDS到下一代传输架构整理
中间件·架构
理人综艺好会1 天前
路由中间件快速了解(Gin版)
中间件·gin
lifewange2 天前
MQ中间件是什么
中间件
小邓的技术笔记2 天前
聊聊 ASP.NET Core 中间件和过滤器的区别
后端·中间件·asp.net
8Qi83 天前
微服务通信:同步 vs 异步与MQ选型指南
java·分布式·微服务·云原生·中间件·架构·rabbitmq
初中就开始混世的大魔王4 天前
3.2 DDS 层-Domain
开发语言·c++·中间件
2601_949814174 天前
docker离线安装及部署各类中间件(x86系统架构)
docker·中间件·系统架构