For example, if the url is not match to any API endpoint, we want to return 404 error message.
So first thing, we want to send the request to the server first. If got the response, then we just return it back.
self.addEventListener('fetch', (event) => { event.respondWith( fetch(event.request).then( (response) => { // fetch the request frist return response; }) ) });
Then we handle 404 error:
self.addEventListener('fetch', (event) => { event.respondWith( fetch(event.request).then( (response) => { if(response.status === 404){ return fetch('/img/dr-evil.gif'); } return response; }).catch( () => { return new Response("Something totally wrong"); }) ) });