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

相关推荐
失败又激情的man1 天前
Scrapy进阶封装(第四阶段:中间件设置,动态UA,ip代理池)
爬虫·scrapy·中间件
亲爱的非洲野猪1 天前
Kafka消息积压的多维度解决方案:超越简单扩容的完整策略
java·分布式·中间件·kafka
摘星编程1 天前
深入理解责任链模式:从HTTP中间件到异常处理的实战应用
http·设计模式·中间件·责任链模式·实战应用
~山有木兮3 天前
LiteHub中间件之限流实现
网络·http·中间件
fo安方3 天前
运维的利器–监控–zabbix–第三步:配置zabbix–中间件–Tomcat–步骤+验证
运维·中间件·zabbix
Code季风4 天前
Gin 中间件详解与实践
学习·中间件·golang·go·gin
一只程序汪4 天前
【如何实现分布式压测中间件】
分布式·中间件
William一直在路上4 天前
主流分布式中间件及其选型
分布式·中间件
listhi52014 天前
深入浅出Node.js中间件机制
中间件·node.js