February 2018
Intermediate to advanced
298 pages
8h 22m
English
It is possible that your worker might throw an error because of malformed data sent by the main script. In that case, the onerror method of the worker is called in the main script:
// script.jsconst awesomeworker = new Worker('myworker.js');awesomeworker.postMessage({task: "divide", num1: 5, num2: 0})awesomeworker.addEventListener('error', e => { console.log(e); // information of ErrorEvent});
Here, we attached an error event listener, and for now, we're just logging it to the console. You might want to send it to a server to actually log it for further analysis in a production app.
The worker is as follows:
// myworker.jsself.addEventListener('message', e => { if(e.data.num2 == 0) { throw "Cannot divide by 0";Read now
Unlock full access