rcjsdev
rcjsdev

Reputation: 843

Using service worker to catch network error

I have a service worker for my site, but I'm not sure how to get it to handle when there is a network error, I've looked through Mozilla's guides but when I run the worker offline it says that a network error was passed to the respondWith function, and the catch promise seems to not respond with the cached data.

this.addEventListener('install', function(event) {
  event.waitUntil(
    caches.open('v1').then(function(cache) {
      return cache.addAll([
        '/',
        '/favicon.ico',
        '/f3be2e30f119a1a9b0fdee9fc1f477a9',
        '/index.html',
        '/sw.js'
      ]);
    })
  );
});

this.addEventListener('fetch', function(event) {
    var response;
    event.respondWith(caches.match(event.request).catch(function() {
        return fetch(event.request);
    })).then(function(r) {
        response = r;
        caches.open('v1').then(function(cache) {
            cache.put(event.request, response);
        });
        return response.clone();
    }).catch(function(event) {
        console.log(event, 'borken');
        return caches.match(event.request);
    });
});

The error log is shown here: Error log

Upvotes: 4

Views: 2336

Answers (1)

Marco Castelluccio
Marco Castelluccio

Reputation: 10782

You're calling then on the result of the call to event.respondWith, which is undefined.

You should chain your then call after the call to catch:

var response;
event.respondWith(
  caches.match(event.request)
  .catch(function() {
    return fetch(event.request);
  })
  .then(function(r) {
    response = r;

Not:

var response;
event.respondWith(
  caches.match(event.request)
  .catch(function() {
    return fetch(event.request);
  })
)
.then(function(r) {
  response = r;

Upvotes: 5

Related Questions