5

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;
});
5
  • 2
    Its inside settimeout, once you set things inside settimeout they are going out of the scope. your gonna need to use try/catch inside that settimeout to catch it and handle it.
    – Talg123
    Mar 23, 2020 at 15:44
  • I just tried puting the main() outside, still not working. Mar 23, 2020 at 15:47
  • 1
    Still, your not catching it and not handling it. if you throw an error you need to catch it and then do what ever u wish with it. you can console.log it or if you dont catch it, it bubble up till it throw the process
    – Talg123
    Mar 23, 2020 at 15:51
  • If main() itself is returning a rejected promise, then you can just .catch() that and handle it. If the unhandled rejection is inside of main and not propagated out, then you have to find where that is in the main() code and handle the error appropriately. There is no substitute for writing correct error handling unless you want to just let the process/thread abort because of it.
    – jfriend00
    Mar 23, 2020 at 16:56
  • 3
    I had the same problem and it's not a case of faulty error handling. Apparently this unexpected behavior is by design. It is discussed here in the nodejs issues log, along with a workaround: github.com/nodejs/node/issues/33834
    – GGGforce
    Jan 21, 2021 at 17:38

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Browse other questions tagged or ask your own question.