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?