1

the code below will not trigger window.onerror, despite json() failing because the endpoint did not return valid json, and nobody is catching the error, so why isn't window.onerror invoked? jsfiddle: https://jsfiddle.net/f287sn05/

code:

window.onerror=function(error){
    alert("errorhandler 1: "+error);
}
if(1){
window.addEventListener("error",function(error){
    alert("errorhandler 2: "+error);
});
}

(async function(){
let foo= ((await ( await fetch("/no_json_plz_i_want_an_error")).json()));
})();
hanshenrik
  • 19,904
  • 4
  • 43
  • 89
  • 3
    Short answer is because the error occurs in a promise context. You need a try/catch for the await and catch it yourself.... https://jsfiddle.net/t4pfsn75/ – charlietfl Aug 04 '21 at 01:18

1 Answers1

1

to catch errors in async functions you can use try catch blocks, check it out:

(async function(){
  try{
    let foo= ((await ( await fetch("/no_json_plz_i_want_an_error")).json()));
  }
  catch(error){
    console.log(error)
  }
})();
sonEtLumiere
  • 4,461
  • 3
  • 8
  • 35