1. 10
    Show an Error when a POST or DELETE Fails in an Offline PWA
    2m 33s

Show an Error when a POST or DELETE Fails in an Offline PWA

InstructorChris Achard

Share this video with your friends

Send Tweet

We're storing JSON data in the cache - but that only applies to HTTP GET requests - and not to POST or DELETE requests.

We'll add a fetch event listener to the service worker, where we can intercept all fetch requests in our app. We'll forward them to the server - but if they fail, then we'll return an error back to the app.

In the app, we can detect that error, and respond by showing an alert that the functionality isn't available in offline mode.

Nesta Xu
~ 6 years ago

self.addEventListener('fetch', event => { if(event.request.method === "POST" || event.request.method === "DELETE") { event.respondWith( fetch(event.request).catch(err => { return new Response( JSON.stringify({ error: "This action disabled while app is offline" }), { headers: { 'Content-Type': 'application/json' } } ) }) ) } })

The code above appears to be capturing all types of exceptions/errors and returning them as offline errors?