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

如何在不使用认证模块的NestJS Guard中抛出自定义错误?

在NestJS Guard中抛出自定义错误(不使用认证模块)

要实现Guard判断用户不存在时抛出自定义错误,只需把原来返回false的逻辑改成直接抛出你定义好的异常类即可,无需依赖任何认证模块。修改后的完整代码如下:

import { CanActivate, Injectable, ExecutionContext } from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose';
import { Model } from 'mongoose';
import { UserParamsNotFoundException } from 'src/statusResponse/error.response';
// 请替换为实际的Users实体和CreateUser类型导入路径
import { Users } from './path-to-users-model';
import { CreateUser } from './path-to-createuser-dto';

@Injectable()
export class UserGuard implements CanActivate {
    constructor(
        @InjectModel(Users.name) private userModel: Model<CreateUser>,
    ) {}
    
    async canActivate(context: ExecutionContext): Promise<boolean> {
        const request = context.switchToHttp().getRequest();
        const { user } = request.body;

        // 替换成实际的用户存在性校验逻辑,比如根据用户标识查询数据库
        const isUserExist = await this.userModel.exists({ /* 填写查询条件,如id: user.id */ });

        // 用户不存在时直接抛出自定义异常
        if (!isUserExist) {
            throw new UserParamsNotFoundException();
        }

        // 用户存在则返回true,允许请求继续执行
        return true;
    }
};

关键修改说明

  • 移除了无用的NotFoundException导入,改用你自定义的UserParamsNotFoundException
  • 把占位的判断函数替换为实际的数据库查询逻辑(用exists方法判断用户存在性更高效)
  • 不再返回false,而是在用户不存在时直接抛出异常,NestJS会自动将其转化为对应HTTP响应
  • 确保你的UserParamsNotFoundException已正确配置状态码和错误信息,示例如下:
    // src/statusResponse/error.response.ts 示例代码
    import { HttpException, HttpStatus } from '@nestjs/common';
    
    export class UserParamsNotFoundException extends HttpException {
      constructor() {
        super('用户不存在', HttpStatus.NOT_FOUND);
      }
    }
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 18:26:03