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

NestJS中如何转换异常类型?登录场景替换404为401异常

问题修复方案

你的代码核心问题是异步函数调用未使用await,导致get_user抛出的异常无法被login的try/catch块捕获:

  1. get_user是async函数,调用时必须加await,否则它会直接返回一个Promise,内部的异常会变成未处理的Promise拒绝,不会进入外层的catch逻辑。
  2. 如果db.user.findOrThrow是异步操作(数据库查询通常都是异步的),get_user里的调用也需要加await,否则同样无法捕获数据库抛出的异常。

修复后的代码:

async get_user(email){
  try {
    // 若findOrThrow是异步操作,必须加await
    await db.user.findOrThrow(email);
  } catch (e) { 
    throw new NotFoundException;
  }
}

async login (email) {
  try {
    // 必须加await才能捕获get_user的异步异常
    await get_user(email);
  } catch (e) {
    // 仅针对NotFoundException转换,避免掩盖其他错误
    if (e instanceof NotFoundException) {
      throw new UnauthorisedException;
    }
    // 其他异常原样抛出
    throw e;
  }
}

额外说明:

  • 建议在catch块里判断异常类型,只将NotFoundException转换为UnauthorisedException,这样其他类型的错误(比如数据库连接失败)会正常抛出,不会被误转为授权错误。
  • 修复后,当用户不存在时,login会正确抛出UnauthorisedException,接口返回401状态码。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.26 19:12:07