NestJS中如何转换异常类型?登录场景替换404为401异常
问题修复方案
你的代码核心问题是异步函数调用未使用await,导致get_user抛出的异常无法被login的try/catch块捕获:
get_user是async函数,调用时必须加await,否则它会直接返回一个Promise,内部的异常会变成未处理的Promise拒绝,不会进入外层的catch逻辑。- 如果
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
相关产品推荐
相关产品推荐

