Error handling in workers

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";

Get Learn ECMAScript - Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.