Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

340
Vistas
Every thrown error ends up in catch block even tho it has to thrown error before that and stop the rest of the code
    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");
    }
}

Wanted result:

  1. If UserId is valid but non-existing in DB throw first error
  2. If UserId is not valid or any other type of error throw second error

Current result:

  1. If UserId is valid but non-existing in DB throw SECOND error
  2. If UserId is not valid or any other type of error throw second error
about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

Well you're throwing an exception inside a try block, which will be caught, and your catch block then re-throws a different exception. You can either inspect the caught exception

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")
    }
}

(Checking an e.code you put on the error with Object.assign, or testing for an Error subclass with instanceof, would be nicer than testing the message)

or put the try closer around the await … statement whose errors you want to handle:

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
}

which is nicer with .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
}
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda