Error handling for failed network requests with service workers

Error handling for failed network requests with service workers

Most service worker code samples show only the happy path where the fetched resource will eventually be available, eg:

self.addEventListener('fetch', event => {
  // Skip cross-origin requests, like those for Google Analytics.
  if (event.request.url.startsWith(self.location.origin)) {
    event.respondWith(
      caches.match(event.request).then(cachedResponse => {
        if (cachedResponse) {
          return cachedResponse;
        }

        return caches.open(RUNTIME).then(cache => {
          return fetch(event.request).then(response => {
            // Put a copy of the response in the runtime cache.
            return cache.put(event.request, response.clone()).then(() => {
              return response;
            });
          });
        });
      })
    );
  }
});

Source: https://googlechrome.github.io/samples/service-worker/basic/

But there are a couple of things that can go wrong with respect to network requests for which the service worker API unfortunately has different error handling mechanisms.

To be clear, I’m talking about a network request failing in the “fetch” part:

return fetch(event.request).then(response => {
....
});

Without error handling, there will be an entry in the browser console logs but the error is never propagated to the request issuer in the web page, eg. Javascript code in the main page. Proper error handling needs to catch the error and return an error response to the main window:

return fetch(e.request).catch(function(e){
   var init = { "status" : 500 , "statusText" : "offline" };
   return new Response("",init);
});

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s