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

相关推荐
吳所畏惧8 小时前
Linux环境/麒麟V10SP3下离线安装Redis、修改默认密码并设置Redis开机自启动
linux·运维·服务器·redis·中间件·架构·ssh
慧一居士10 小时前
xxl-job服务搭建,以及 springboot 集成xxl-job 项目完整步骤示例
分布式·中间件
odoo中国13 小时前
Pgpool-II 在 PostgreSQL 中的用例场景与优势
数据库·postgresql·中间件·pgpool
yuanmenghao18 小时前
自动驾驶中间件iceoryx - 内存与 Chunk 管理(三)
数据结构·c++·算法·链表·中间件·自动驾驶
源代码•宸21 小时前
goframe框架签到系统项目开发(补签逻辑实现、编写Lua脚本实现断签提醒功能、简历示例)
数据库·后端·中间件·go·lua·跨域·refreshtoken
忧郁蓝调262 天前
Redis单节点主从复制数据迁移
数据库·redis·缓存·云原生·中间件·云计算·paas
Code Slacker2 天前
西安交通大学软件学院——分布式系统练习题(选择题)
中间件·期末复习·分布式系统·练习题
拆房老料2 天前
BaseMetas Fileview 开源在线文件预览引擎首发:面向社区,免费赋能
中间件·开源·开源软件
transitory_truth3 天前
Apollo使用记录
java·中间件
yuanmenghao3 天前
自动驾驶中间件iceoryx - 内存与 Chunk 管理(一)
c++·vscode·算法·链表·中间件·自动驾驶·柔性数组