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");
}
}
想要的结果:
- 如果UserId是有效的,但在数据库中不存在抛出第一个错误
- 如果UserId无效或任何其他类型的错误抛出第二个错误
当前结果:
- 如果UserId是有效的,但在数据库中不存在抛出第二个错误
- 如果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
}