每个抛出的错误都在catch块中结束,即使它必须在此之前抛出错误并停止其余的代码


async deleteUser(userId: string): Promise<boolean> {
try {
const userToDelete = await userModel.findByIdAndDelete(userId)
if(!userToDelete) {
throw new Error(`User with id: ${userId} does not exist`)
}
return true
} catch {
throw new Error("Something wrong with the database");
}
}

想要的结果:

  1. 如果UserId是有效的,但在数据库中不存在抛出第一个错误
  2. 如果UserId无效或任何其他类型的错误抛出第二个错误

当前结果:

  1. 如果UserId是有效的,但在数据库中不存在抛出第二个错误
  2. 如果UserId无效或任何其他类型的错误抛出第二个错误

你在try块内throw一个异常,它将被捕获,然后你的catch块重新抛出一个不同的异常。您可以检查捕获的异常

async deleteUser(userId: string): Promise<boolean> {
try {
const userToDelete = await userModel.findByIdAndDelete(userId)
if (!userToDelete) {
throw new Error(`User with id: ${userId} does not exist`)
}
return true
} catch(e) {
if (e.message == `User with id: ${userId} does not exist`) throw e
else throw new Error("Something wrong with the database")
}
}

(检查您使用Object.assign添加错误的e.code,或使用instanceof测试Error子类,将比测试消息更好)

或者将try放在想要处理错误的await …语句附近:

async deleteUser(userId: string): Promise<boolean> {
let userToDelete
try {
userToDelete = await userModel.findByIdAndDelete(userId)
} catch {
throw new Error("Something wrong with the database");
}
if (!userToDelete) {
throw new Error(`User with id: ${userId} does not exist`)
}
return true
}

.catch():

比较好
async deleteUser(userId: string): Promise<boolean> {
const userToDelete = await userModel.findByIdAndDelete(userId).catch(e => {
throw new Error("Something wrong with the database");
})
if (!userToDelete) {
throw new Error(`User with id: ${userId} does not exist`)
}
return true
}

相关内容

  • 没有找到相关文章

最新更新