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

282
Vistas
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 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