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

NestJS登录接口返回201 OK状态码,却提示未授权错误

NestJS登录接口HTTP状态码异常问题修复

你的问题出在catch块的处理逻辑上:直接return error会让Nest把异常对象当作普通响应数据返回,而非触发框架的异常处理机制,导致GlobalPipes和内置异常过滤器无法生效,状态码自然不符合预期。

修复方案

去掉try-catch块(推荐),让Nest自动捕获并处理抛出的异常:

async login(dto: LoginDto) {
  const user = await this.prisma.user.findUnique({
    where: {
      email: dto.email,
    },
  });

  if (!user) throw new ForbiddenException('Credentials incorrect');

  const pwMatches = await argon.verify(user.password, dto.password);

  if (!pwMatches) throw new ForbiddenException('Credentials incorrect');
  
  return this.signToken(user.id, user.email);
}

如果确实需要保留try-catch(比如要做额外的错误日志),需在catch块中重新抛出异常,让Nest处理:

async login(dto: LoginDto) {
  try {
    const user = await this.prisma.user.findUnique({
      where: {
        email: dto.email,
      },
    });

    if (!user) throw new ForbiddenException('Credentials incorrect');

    const pwMatches = await argon.verify(user.password, dto.password);

    if (!pwMatches) throw new ForbiddenException('Credentials incorrect');
    
    return this.signToken(user.id, user.email);
  } catch (error) {
    // 可在此添加日志记录等额外逻辑
    throw error; // 重新抛出异常,触发Nest的异常处理流程
  }
}

原理说明

Nest的异常处理机制基于抛出异常而非返回异常对象。只有当异常被抛出时,才会被内置的ExceptionFilter或你配置的全局过滤器拦截,进而返回对应的HTTP状态码(比如ForbiddenException对应403)和格式化后的错误响应。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.15 15:12:38