1

How to handle/throw errors in a shared web worker?

If you throw an error like this in a dedicated web worker the error appears in the console in the browser.. but not when the worker is shared..!?

With a dedicated web worker you can also use console.log() in the worker.. but not in a shared web worker

main page

var worker = new SharedWorker('js/webworker.js'); worker.port.onmessage = function(e){ console.log('From worker: '+e.data); }; worker.port.onerror = function(e){ console.log(e.message+'\nLine: '+e.lineno+'\nFilename: '+e.filename); }; worker.port.start(); worker.port.postMessage('This message should throw an error in the web worker'); 

shared web worker

var ports = []; self.onconnect = function(e){ var port = e.ports[0]; ports.push(port); port.onmessage = function(e){ port.postMessage(e.data); throw Error('hehehe'); }; port.start(); port.postMessage('Worker connected!'); }; 

2 Answers 2

6

As the documentation says:

Whenever an uncaught runtime script error occurs in one of the worker's scripts, if the error did not occur while handling a previous script error, the user agent must report the error at the URL of the resource that contained the script, with the position (line number and column number) where the error occurred, in the origin of the scripts running in the worker, using the WorkerGlobalScope object's onerror attribute.

http://www.w3.org/TR/workers/

So the error will be reported to self and then sent to all the ports:

self.onerror = function (e) { ports.forEach(function (port) { port.postMessage(e); }); }; 

Here is jsfiddle that demonstrates it: http://jsfiddle.net/nhrfgd1L/

Sign up to request clarification or add additional context in comments.

1 Comment

worker.onerror does not get triggered (on Chrome 107). worker.onmessage error handling does get triggered by the ports.forEach(i=>i.postMessage(e)).
0

(July 2021)

As an update to the already given answer, for Sharedworkers it is enough to write the respective event handler on the client side only (the web pages) as indicated here: https://developer.mozilla.org/en-US/docs/Web/API/SharedWorker/onerror

Basically, it is this function:

worker.onerror = function(error) { console.log('Worker error: ' + error.message + '\n'); }; 

The error.message contains the details of the error if you want to display them or put them in a log.

The Sharedworker itself does not need to have any additional code to manage errors.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.