Home > front end >  How to hide stack trace from service worker fetch?
How to hide stack trace from service worker fetch?

Time:12-25

I have service worker like this:

self.addEventListener('fetch', function (event) {
    event.respondWith(new Promise(function(resolve, reject) {
       // ...
       fetch(event.request).then(resolve).catch(reject);
    }));
});

I don't remember where I found this code, but when I use ad blocker together with 404, in console I see stack trace:

Service worker Stack Trace in Dev console

Is there a way to get rid of that stack trace. I only need to know that the fetch failed (see the second error message).

CodePudding user response:

Just clear the stack property:

const e = new Error('Uh oh');
console.log(e.name, e.message, e.stack);

e.stack = '';
console.log(e.name, e.message, e.stack);

CodePudding user response:

The stack trace is coming from the stack property of the Error object (or derived class) that is passed to the reject method. One solution is to reject with a string:

catch( err=>reject(err.message))

If, however, you want more information about the url that failed to fetch you would need to include it from information in event.request. How to include it depends on whether event.request is a url string, URL or Request object or object with a stringifier. Without exact information you could try something like

catch( err=>reject("Fetch failed to fetch "   (request?.url || request )));


 
  • Related