diff --git a/documentation/docs/30-advanced/40-service-workers.md b/documentation/docs/30-advanced/40-service-workers.md index 33c90f663289..a4888a6ac8de 100644 --- a/documentation/docs/30-advanced/40-service-workers.md +++ b/documentation/docs/30-advanced/40-service-workers.md @@ -66,7 +66,11 @@ self.addEventListener('fetch', (event) => { // `build`/`files` can always be served from the cache if (ASSETS.includes(url.pathname)) { - return cache.match(url.pathname); + const response = await cache.match(url.pathname); + + if (response) { + return response; + } } // for everything else, try the network first, but @@ -74,13 +78,27 @@ self.addEventListener('fetch', (event) => { try { const response = await fetch(event.request); + // if we're offline, fetch can return a value that is not a Response + // instead of throwing - and we can't pass this non-Response to respondWith + if (!(response instanceof Response)) { + throw new Error('invalid response from fetch'); + } + if (response.status === 200) { cache.put(event.request, response.clone()); } return response; - } catch { - return cache.match(event.request); + } catch (err) { + const response = await cache.match(event.request); + + if (response) { + return response; + } + + // if there's no cache, then just error out + // as there is nothing we can do to respond to this request + throw err; } }