Search code examples
javascriptweb-worker

Web worker onerror


Do web workers provide some method of finding out what data was posted to them if they fail?

So if I have the following code is there anyway to find out the contents of someData in the onerror handler if it fails or would I just have to keep track of it?

var someData = {...};
myWorker.postMessage(someData);

Solution

  • Web workers do not provide any dedicated method of finding out what data was posted to them if they fail.

    But that's quite easy to do manually, you can either handle onerror from outside, or do the deeper inspection in the onmessage handler from inside of the worker (where you have access to the message event):

    // this one-liner was wrapped in order to improve legibility
    var w = new Worker( URL.createObjectURL(
        new Blob([ " self.onmessage = function (evt) {\
            console.log(evt.data);\
            throw new Error('SOMETHING.WENT.WRONG.'); } "
        ])
    ));
    w.onerror = function (err) {
        console.log('worker is suffering!', err)
    };
    w.postMessage(123);