【问题标题】:why doesn't fetch().json() errors trigger window.onerror?为什么 fetch().json() 错误不会触发 window.onerror?
【发布时间】:2021-08-04 01:13:05
【问题描述】:

下面的代码不会触发 window.onerror,尽管 json() 失败是因为端点没有返回有效的 json,并且没有人捕捉到错误,那么为什么不调用 window.onerror 呢? jsfiddle:https://jsfiddle.net/f287sn05/

代码:

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()));
})();

【问题讨论】:

  • 简短答案是因为错误发生在承诺上下文中。你需要一个 try/catch 来等待并自己捕捉它......jsfiddle.net/t4pfsn75

标签: javascript error-handling fetch


【解决方案1】:

要捕获异步函数中的错误,您可以使用 try catch 块,检查一下:

(async function(){
  try{
    let foo= ((await ( await fetch("/no_json_plz_i_want_an_error")).json()));
  }
  catch(error){
    console.log(error)
  }
})();

【讨论】:

  • 有用的信息,但它并没有真正回答问题why^^
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-07-26
  • 2021-11-07
  • 2014-09-15
  • 1970-01-01
  • 2013-04-19
  • 2013-12-15
  • 1970-01-01
相关资源
最近更新 更多