worker.on('error') not working when unhandled rejection happens in the worker

Viewed 1891

worker.js

async function main() {
  throw new Error('Bullocks!');
}

setTimeout(async () => {
  await main();
}, 1000);

main.js

const { Worker } = require('worker_threads');

const worker = new Worker('./worker.js');
worker.on('error', err => {
  console.log('error happened on the worker');
});

Why that error handler on the main.js is not called, instead it just prints the error.

(node:26000) UnhandledPromiseRejectionWarning: Error: Bullocks!

I've used this solution and works: throwing the error when unhandled rejection happens, but is there any "proper" solution for this?

async function main() {
  throw new Error('Bullocks!');
}

setTimeout(async () => {
  await main();
}, 1000);

process.on('unhandledRejection', err => {
  throw err;
});
0 Answers
Related