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

289
Visualizações
An exception launched in a Promise is not captured in the catch() method

I throw an exception in the asynchronous code inside the Promise. The exception isn't captured in the catch() method

let x = new Promise((resolve,reject)=>{setTimeout(()=>{throw new Error(5);},3000)}).catch((error)=>{console.log(error)})

Instead with this code:

let x = new Promise((resolve,reject)=>{setTimeout(()=>{reject( new Error(5));},3000)}).catch((error)=>{console.log(error)})

with the Error in the reject ,is intercepted in the catch() method. (I executed the code in the console of my browser, and I observed this behavior) What does it mean? Thus, if an exception is launched from JSON.parse() and un exception is tried, will not be captured? And if it's like that, how can I handle this situation? I mean this situation, in the case that JSON.parse() launch an exception because the format of the file returned from the server isn't properly formatted like JSON.:

function APIRequest(){
return new Promise((resolve,reject)=>{

let xhr = new XMLHttpRequest();
xhr.onreadystatechange = function(){
  if (xhr.readyState == 4) {
                if (xhr.status >= 200 && xhr.status<299 || xhr.status == 304) {
                    let response = JSON.parse(xhr.responseText);
                    resolve(response);
                } else {
                    reject('something is gone wrong')
                }
}
xhr.open('GET','URL_REQUEST);
xhr.send(null);

});
}

(I know that there is fetch(), it's an example...) Should I use a old try-catch around JSON.parse and in the old catch block do reject(error)? Or is there a more clean solution?

about 4 years ago · Juan Pablo Isaza
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