通过服务工作者消息事件引发的捕获例外
我无法发现服务工作者的消息事件引发的异常。.
客户使用以下代码在SW上执行命令:
import { messageSW } from "workbox-window";
// .. code for Workbox initialization/registration omitted
messageSW(registration?.active, { type: "SYNC" })
.then((results) => {
console.log("done");
})
.catch((e) => {
console.error(e);
});
在SW(sw.js
)方面,我有以下代码:
self.addEventListener("message", async (event) => {
if (requestType === "SYNC") {
event.ports[0].postMessage(await longRunningTask());
}
});
只要SW不抛出任何例外,该解决方案就可以了。这意味着在执行SW上的长期运行过程之后,客户端打印了“ 完成”消息。 如果抛出了例外,什么都没有返回。
我设法通过执行以下操作来解决问题:
self.addEventListener("message", async (event) => {
if (requestType === "SYNC") {
try {
event.ports[0].postMessage(await longRunningTask());
} catch (error) {
event.ports[0].postMessage(error);
}
}
});
在这种情况下 - 结果总是返回,无论如何完成 “是印刷的,但是:
- 我如何从服务工作者那里产生例外,以便客户可以抓住和处理?
- 总的来说,很高兴听到我正在做的事情是否是一种适当的方法,即如何从客户中调用SW上的异步代码...
I can't catch an exception thrown by the service worker's message event..
The client uses following code to execute the command on the SW:
import { messageSW } from "workbox-window";
// .. code for Workbox initialization/registration omitted
messageSW(registration?.active, { type: "SYNC" })
.then((results) => {
console.log("done");
})
.catch((e) => {
console.error(e);
});
On the SW (sw.js
) side I have the following code:
self.addEventListener("message", async (event) => {
if (requestType === "SYNC") {
event.ports[0].postMessage(await longRunningTask());
}
});
This solution works OK as long as the SW is not throwing any exceptions. Meaning that the client prints the "done" message after the long running process on the SW is executed. If the exception is thrown nothing gets returned, ever.
I have managed to fix the problem by doing the following:
self.addEventListener("message", async (event) => {
if (requestType === "SYNC") {
try {
event.ports[0].postMessage(await longRunningTask());
} catch (error) {
event.ports[0].postMessage(error);
}
}
});
In this case - the result is always returned regardless, "done" is printed, but:
- how do I actually produce an exception from the service worker, so the client could catch and handle it?
- In general it would be good to hear if what I am doing is an appropriate approach to how asynchronous code on the SW shall be invoked from the client...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这是我自己的解决方案,最终使用:
在服务工作者端 - 助手方法:
当抓取异常时,我们设置了错误属性。使用AS:
在客户端请求包装器上:
魔术是读取错误属性并在情况下拒绝承诺(因此导致异常被抛弃)。使用为
Here is my own solution I ended up using:
On service worker side - helper method:
When exception is caught we set the error property. Use as:
On client side request wrapper:
The magic here is to read the error property and reject the promise if that is the case (hence causing an exception to be thrown). Use as