You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在NestJS Swagger中全局定义API响应及统一配置500错误?

全局配置Swagger默认显示500 Internal Server Error响应

如果你用的是NestJS + Swagger,有几种实用的全局配置方式,不用给每个控制器方法单独加@ApiInternalServerErrorResponse():

方法一:通过基础控制器继承

定义一个带全局错误响应的基础控制器,所有业务控制器继承它即可自动继承Swagger配置:

import { Controller } from '@nestjs/common';
import { ApiInternalServerErrorResponse } from '@nestjs/swagger';

// 基础控制器,添加500错误响应的Swagger注解
@ApiInternalServerErrorResponse({ description: '服务器内部错误' })
export class BaseController {}

// 业务控制器继承基础控制器,所有接口自动带上500响应文档
@Controller('users')
export class UsersController extends BaseController {
  // 这里的接口方法无需额外添加装饰器
}

方法二:全局注册自定义装饰器

创建一个包含500响应的自定义装饰器,然后通过NestJS的全局提供者注册,让所有控制器自动应用:

  1. 先写自定义装饰器:
import { applyDecorators } from '@nestjs/common';
import { ApiInternalServerErrorResponse } from '@nestjs/swagger';

export const GlobalApiErrorResponses = () => {
  return applyDecorators(
    ApiInternalServerErrorResponse({ description: '服务器内部错误' })
    // 还可以追加其他全局通用响应,比如400参数错误、401未授权等
  );
};
  1. 在app.module.ts中全局注册这个装饰器:
import { Module, APP_DECORATOR } from '@nestjs/common';
import { GlobalApiErrorResponses } from './decorators/global-api-responses.decorator';

@Module({
  providers: [
    {
      provide: APP_DECORATOR,
      useValue: GlobalApiErrorResponses(),
    },
  ],
})
export class AppModule {}

方法三:生成Swagger文档时手动注入

直接在生成Swagger文档的逻辑里,遍历所有接口路径,手动添加500响应配置,无需修改控制器代码:

async function bootstrap() {
  const app = await NestFactory.create(AppModule);

  const swaggerConfig = new DocumentBuilder()
    .setTitle('你的API文档')
    .setDescription('API功能描述')
    .setVersion('1.0')
    .build();
  
  const swaggerDocument = SwaggerModule.createDocument(app, swaggerConfig);
  
  // 遍历所有路径和请求方法,添加500错误响应
  Object.keys(swaggerDocument.paths).forEach(path => {
    Object.keys(swaggerDocument.paths[path]).forEach(method => {
      swaggerDocument.paths[path][method].responses['500'] = {
        description: '服务器内部错误',
        // 可选:定义错误响应体结构
        schema: {
          type: 'object',
          properties: {
            statusCode: { type: 'number' },
            message: { type: 'string' },
            error: { type: 'string' },
          },
        },
      };
    });
  });

  SwaggerModule.setup('api-docs', app, swaggerDocument);

  await app.listen(3000);
}
bootstrap();

内容的提问来源于stack exchange,提问作者lawayben

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.17 04:25:12