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

179
Visualizações
JS Multiple Nested Try...Catch Blocks

I have a function which needs to perform multiple promises in a strict order, and if any one were to fail, the whole function needs to error out. I'm understanding that I should use a Try...Catch block to catch any exceptions which get thrown.

Currently, I am using a nested try...catch like:

try {
  try {
    code1()
  } catch(err) {
    console.log("Inner 1 ", err)
    throw err
  }

  try {
    code2()
  } catch(err) {
    console.log("Inner 2 ", err)
    throw err
  }
} catch(err) {
  console.log("Outer", err)
} finally {
  console.log("Full Success")
}

The intention here is that if either code1() or code2() were to fail, the outer catch would trigger. If both code1 and code2 were to success, the outer finally block would trigger.

However, it seems, right now, no matter if code1 or code2 succeed, the outer finally is always being trigger in addition to the associated inner catch statements.

Is there any way to get the outer catch to trigger?

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Turns out, thanks to @Barmar 's comment, the finally block will always execute, that's why my code was always throwing the finally. Instead, I moved the "full success" into the outer try block.

try {
  try {
    code1()
  } catch(err) {
    console.log("Inner 1 ", err)
    throw err
  }

  try {
    code2()
  } catch(err) {
    console.log("Inner 2 ", err)
    throw err
  }

  console.log("Full Success")
} catch(err) {
  console.log("Outer", err)
}

Now, it appears to be working as intended.

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