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

相关推荐
聊聊MES那点事6 小时前
Cogent DataHub vs Kepware,两大工业数据中间件的深度对比分析
开发语言·中间件·opc·opc ua
千鼎数字孪生-可视化6 小时前
智能制造中的中间件作用:融通设备、系统和云平台
中间件·制造·智能制造
千汇数据的老司机6 小时前
边缘存储+中间件协同策略:实现设备数据高效处理与低延迟响应
中间件
jc06201 天前
4.4-中间件之gRPC
c++·中间件·rpc
thginWalker2 天前
中间件常用组件的原理和设计
中间件
奥尔特星云大使3 天前
mysql读写分离中间件——Atlas详解
数据库·mysql·中间件·dba·读写分离
2301_772093563 天前
Fastdfs_MinIO_腾讯COS_具体逻辑解析
数据库·redis·分布式·中间件
奥尔特星云大使4 天前
读写分离中间件简介
数据库·mysql·中间件·读写分离
友莘居士4 天前
高效处理 Excel 海量数据入库:编程脚本、CSV 中间件、图形工具优化全攻略
数据库·中间件·excel·csv·海量数据·入库
jc06204 天前
4.3-中间件之Kafka
分布式·中间件·kafka