0

I have a problem in my application and I'd like some help please :)

I'm using a service worker, and I've encountered an error when testing it in the following scenario:

  • I add a non existent file to the list of cached files
  • service worker will become redundant

Now, I understand that a service worker is redundant when:

  • A new service worker is replacing the current service worker
  • the current service worker is being discarded due to an install failure.

I've followed the following stackoverflow answer, specifically this section:

    try
    {
          ok = await cache.addAll(c);
    }
    catch (err)
    {
          console.error('sw: cache.addAll');
          for await (let i of c)
          {
             try
             {
                 ok = await cache.add(i);
             }
             catch (err)
             {
                  console.warn('sw: cache.add',i);
             }
          }
   }

What I'd like to do is basically to be able to determine:

  • if the service worker is redundant because of a failed installation (i.e, take the example above of a non existent file added to the list of cached files)
  • if the service worker is redundant because a new worker is replacing the current worker

How can I achieve it? I tried to throw an error inside the catch of the code provided and adding a try catch in the code where I'm registering the worker but I can't catch it.

Basically something like:

service worker file

        try
        {
              ok = await cache.addAll(c);
        }
        catch (err)
        {
              console.error('sw: cache.addAll');
              for await (let i of c)
              {
                 try
                 {
                     ok = await cache.add(i);
                 }
                 catch (err)
                 {
                      console.warn('sw: cache.add',i);
                 }
              }
             throw new Error ('Error when caching files');
       }

Where I register the worker

try
{
    navigator.serviceWorker.register("/sw.js", {
         //OTHER CODE
    });
}
catch (error)
{
    console.log(error);
}
giovandrea
  • 197
  • 1
  • 4
  • 13

0 Answers0