2016-12-18 89 views
3

我正在使用服務工作者的緩存設施,但是,在更新到站點後,緩存在刷新頁面時仍會提供舊數據。當服務器關閉時,Service Worker會拋出未被捕獲的錯誤

所以按搶答this post我實現了陳舊,同時,重新驗證:

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

當連接,一切似乎都很好,我可以看到控制檯日誌消息。

當我停止服務器並刷新頁面時,我得到一個例外的負載。我添加了fetch()的catch來嘗試和處理異常,但它仍然失敗(並且catch不被調用)。我在caches.open()和respondWith()上添加了一個catch,但同樣的東西。

我知道我可以忽略這些錯誤,但我寧願處理他們,什麼也不做(包括不是他們outputing到控制檯),所以我可以看到我輸出控制檯有意義的東西。

如何停止錯誤信息?

服務安裝時的錯誤不如探測,但這也很好,可以忽略和忽略。

回答

1

添加在無操作.catch()fetch()承諾鏈的末端應防止從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的原生網絡代碼。沒有什麼能夠從JavaScript處理的。

+0

是的,這似乎是不能隱藏的網絡狀態警報的共識:(漁獲仍然沒有工作,但我沒有得到它的工作。看到我的最終代碼。感謝您的幫助。 –

1

我確實把抓住你的地方,我甚至再次嘗試,但仍然錯誤。關鍵原來是then()調用的第二個函數。

這是最終的工作代碼。從我剪切和粘貼後的初始響應處理中也有一個錯誤。這個爲我工作。

self.addEventListener('fetch', function(event) { 
    event.respondWith(caches.open(CACHE_NAME).then(function(cache) { 
     return cache.match(event.request).then(function(response) { 
      //console.log("cache request: " + event.request.url); 
      var fetchPromise = fetch(event.request).then(function(networkResponse) { 
       // if we got a response from the cache, update the cache 
       //console.log("fetch completed: " + event.request.url, networkResponse); 
       if (networkResponse) { 
        //console.debug("updated cached page: " + event.request.url, networkResponse); 
        cache.put(event.request, networkResponse.clone()); 
       } 
       return networkResponse; 
      }, function (e) { 
       // rejected promise - just ignore it, we're offline 
       //console.log("Error in fetch()", e); 
       ; 
      }); 

      // respond from the cache, or the network 
      return response || fetchPromise; 
     }); 
    })); 
}); 
相關問題