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"); } }Resultado buscado:
resultado actual:
Bueno, estás throw una excepción dentro de un bloque de try , que será capturado, y tu bloque catch vuelve a lanzar una excepción diferente. Puede inspeccionar la excepción detectada
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") } } (Comprobar un e.code que puso en el error con Object.assign , o probar una subclase de Error con instanceof , sería mejor que probar el mensaje)
o ponga el try más cerca de la declaración await … cuyos errores desea manejar:
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 } que es mejor con .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 }