Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

341
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda