You need to enable JavaScript to run this app. NestJS自定义@ClientRoles装饰器报错无法在Swagger UI返回正确错误信息
优惠活动
大模型
产品
解决方案
定价
更多

NestJS自定义@ClientRoles装饰器报错无法在Swagger UI返回正确错误信息

问题根因

你遇到的问题本质是@ClientRoles装饰器抛出的错误不属于NestJS内置的HttpException子类,NestJS默认全局异常过滤器只会对HttpException类型的异常按指定状态码返回,非该类型的异常会被统一封装为500内部错误返回,因此才会出现终端能打印正确报错,但Swagger收到500响应的情况。

解决方案
  • 方案一:修改@ClientRoles装饰器实现(可修改私有包代码的前提下优先使用)
    找到private-npm包中@ClientRoles的源码,将原有抛出普通Error的逻辑,替换为抛出NestJS内置的ForbiddenException:
// 装饰器内部逻辑修改示例
import { ForbiddenException } from '@nestjs/common';

// 权限校验不通过时执行
throw new ForbiddenException('Permission not fulfilled');
  • 方案二:新增全局异常过滤器捕获错误(无法修改私有包代码时使用)
  1. 新建全局异常过滤器文件,手动匹配权限不足的错误:
import { ExceptionFilter, Catch, ArgumentsHost, HttpStatus } from '@nestjs/common';
import { Response } from 'express';

@Catch()
export class AllExceptionsFilter implements ExceptionFilter {
  catch(exception: unknown, host: ArgumentsHost) {
    const ctx = host.switchToHttp();
    const response = ctx.getResponse<Response>();
    
    // 匹配权限不足的错误信息
    if (exception instanceof Error && exception.message === 'Permission not fulfilled') {
      return response.status(HttpStatus.FORBIDDEN).json({
        statusCode: HttpStatus.FORBIDDEN,
        message: 'Permission not fulfilled',
        error: 'Forbidden'
      });
    }

    // 其他错误保留原有处理逻辑
    const status = (exception as any)?.status || HttpStatus.INTERNAL_SERVER_ERROR;
    const message = exception instanceof Error ? exception.message : 'Internal server error';

    response.status(status).json({
      statusCode: status,
      message
    });
  }
}
  1. 在项目入口main.ts中注册全局过滤器:
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { AllExceptionsFilter } from './filters/all-exceptions.filter';

async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  app.useGlobalFilters(new AllExceptionsFilter());
  await app.listen(3000);
}
bootstrap();
  • 方案三:补充Swagger响应声明优化调试体验
    在对应控制器方法上添加@ApiForbiddenResponse装饰器,即可在Swagger UI中展示403响应的说明:
import { ApiForbiddenResponse } from '@nestjs/swagger';

// 在控制器方法上新增装饰器
@ClientRoles({ roles: ['test-role'] })
@Get()
@ApiOperation({ title: 'List users' })
@ApiForbiddenResponse({ description: 'Permission not fulfilled' })
async listUsers(): IUser[] {
  return this.service.listUsers(); 
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.11 13:09:02