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

相关推荐
w23617346018 小时前
Nginx中间件的解析
运维·nginx·中间件
weisian15112 小时前
中间件--ClickHouse-10--海量数据存储如何抉择ClickHouse和ES?
clickhouse·elasticsearch·中间件
muyouking111 天前
4.Rust+Axum Tower 中间件实战:从集成到自定义
开发语言·中间件·rust
Cachel wood1 天前
Mysql相关知识2:Mysql隔离级别、MVCC、锁
数据库·python·sql·mysql·中间件·数据分析·django
w23617346012 天前
解析三大中间件:Nginx、Apache与Tomcat
nginx·中间件·tomcat·apache
和尚用0飘柔02 天前
【中间件】redis使用
数据库·redis·中间件
佳腾_2 天前
【消息队列RocketMQ】一、RocketMQ入门核心概念与架构解析
中间件·架构·消息队列·云计算·rocketmq
和尚用0飘柔02 天前
【中间件】nginx将请求负载均衡转发给网关,网关再将请求转发给对应服务
nginx·中间件·负载均衡
MarkHD2 天前
第二十五天 - Web安全防护 - WAF原理与实现 - 练习:请求过滤中间件
安全·web安全·中间件