gpt4 book ai didi

caching - 当服务器关闭时,Service Worker 抛出 Uncaught Error

转载 作者:行者123 更新时间:2023-12-02 01:19:06 25 4
gpt4 key购买 nike

我正在使用服务 worker 的缓存设施,但是,在更新站点后,当我刷新页面时,缓存仍然提供旧数据。

所以根据 this post 中的答案我实现了 stale-while-revalidate:

self.addEventListener('fetch', function(event) {
event.respondWith(caches.open(CACHE_NAME).then(function(cache) {
return cache.match(event.request).then(function(response) {
var fetchPromise = fetch(event.request).then(function(networkResponse) {
// if we got a response from the cache, update the cache
if (response) {
console.log("cached page: " + event.request.url);
cache.put(event.request, networkResponse.clone());
}
return networkResponse;
});

// respond from the cache, or the network
return response || fetchPromise;
});
}));
});

连接后,一切似乎都很好,我可以看到控制台日志消息。

当我停止服务器并刷新页面时,我收到了大量异常。
Uncaught (in promise) TypeError: Failed to fetch
Failed to load resource: net::ERR_CONNECTION_REFUSED

我在 fetch() 上添加了一个捕获来尝试处理异常,但它仍然失败(并且没有调用捕获)。我在 caches.open() 和 respondWith() 上添加了一个捕获,但同样的事情。

我知道我可以忽略这些错误,但我宁愿处理它们而不做任何事情(包括不将它们输出到控制台),这样我就可以在我输出的控制台中看到有意义的内容。

如何停止错误消息?

服务安装时的错误不是一个问题,但这也很好捕获和忽略。

最佳答案

添加无操作 .catch()到最后你的fetch() promise 链应该防止Uncaught (in promise) TypeError: Failed to fetch来自被记录的消息:

var fetchPromise = fetch(event.request).then(function(networkResponse) {
// if we got a response from the cache, update the cache
if (response) {
console.log("cached page: " + event.request.url);
cache.put(event.request, networkResponse.clone());
}
return networkResponse;
}).catch(function() {
// Do nothing.
});

我知道您提到您尝试添加 .catch() ,但也许它没有位于链的正确部分?

我不知道有什么方法可以防止 Failed to load resource: net::ERR_CONNECTION_REFUSED被记录的消息,因为它直接来自 Chrome 的 native 网络代码。您无法从 JavaScript 中“处理”任何事情。

关于caching - 当服务器关闭时,Service Worker 抛出 Uncaught Error ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41209481/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com