Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

290
Views
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
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!