[在提取API的catch块中抛出错误时未触发Web worker onerror事件处理程序

问题描述 投票:0回答:1

TL; DR; Promise(即fetch-api)和webworker全局onerror事件处理程序中的重新抛出错误是否存在问题?

我很难将Web工作者中的提取api引发的错误冒泡给启动Web工作者的客户端。我看到的是“ 未捕获(承诺中的错误)>”,而不是Webworkers self.onerror事件处理程序中的代码。当我在同一Web Worker中的同步函数中引发错误时,它的确会出现在self.onerror事件处理程序中...

为了进一步解释,在我的Webworker内部,我有:

  • onerror事件处理程序
  • 使用获取api调用webapi的函数
  • 我想传递在调用Web api到客户端时遇到的某些错误...因此,我在获取的末尾(在catch块中)抛出了错误。这就是我当前的测试结果:

fetch('https://<server>/api/token?key=version', { method: 'GET', credentials: 'include'})
.then((response) => {
  throw new Error("Oh no - something went wrong");
  return response.json();
})
.then((data) => {
  /* do something with the data in normal flow */
})
.catch((error) => { 
  /* we want to pass along certain types of errors */
  throw(error); /* <---- this is the last error I see logged in F12 debug windows -->
})

但是我从不

看到到达onerror事件处理程序的错误,看起来像这样(只是一些测试输出):
self.onerror = function (event) {
    console.trace(event);
}

我看到(使用F12调试)在获取api捕获的行上记录了未捕获(承诺中的错误)>

)>

我忽略了什么?重新抛出错误和全局onerror事件处理程序存在问题吗?

TL; DR;在Promise(即fetch-api)和Webworker全局onerror事件处理程序中重新抛出错误是否存在问题?我很难冒起读取API引发的错误...

事实证明,有两种方法可以确保promise中的重新抛出错误(fetch-api基于promise :)冒泡了:

1] How to bubble a web worker error in a promise via worker.onerror?中提到的技巧>

->只需将抛出的内容包装在setTimeout

 setTimeout(function() { throw err; });

2)How to catch uncaught exception in Promise中提到的新方法>

->为unhandledrejection

添加一个事件处理程序
self.addEventListener('unhandledrejection', function (event) {
    // the event object has two special properties:
    // event.promise - the promise that generated the error
    // event.reason  - the unhandled error object
    throw event.reason;
});
fetch-api web-worker onerror
1个回答
0
投票

事实证明,有两种方法可以确保promise中的重新抛出错误(fetch-api基于promise :)冒泡了:

© www.soinside.com 2019 - 2024. All rights reserved.