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

相关推荐
cuber膜拜2 天前
LangChain v1.0 Middleware(中间件)使用指南
python·中间件·langchain·langgraph
桂花很香,旭很美4 天前
[7天实战入门Go语言后端] Day 5:中间件与业务分层——日志、鉴权与请求超时
开发语言·中间件·golang
金刚猿4 天前
03_虚拟机中间件部署_Nacos 部署单机模式、配置鉴权
linux·中间件·nacos·配置鉴权
黄俊懿5 天前
【架构师从入门到进阶】第一章:架构设计基础——第二节:架构设计原则
分布式·后端·中间件·架构
花果山总钻风7 天前
SQLAlchemy各种排序示例
后端·python·中间件
weixin_421994787 天前
依赖注入与中间件 - ASP.NET Core 核心概念
后端·中间件·asp.net
PD我是你的真爱粉8 天前
RabbitMQRPC与死信队列
后端·python·中间件
曼岛_9 天前
[Java实战]springboot3项目使用宝蓝德中间件 bes-lite-spring-boot-starter 添加安全头
java·安全·中间件
带娃的IT创业者10 天前
专栏系列04(模块1第4篇) 《蓝图系统与中间件帝国:40+个路由模块的组织哲学》
python·中间件·flask·蓝图·blueprint·python蓝图