skip to content

In Node.js, what happens to a worker_threads.Worker and to the main thread when code inside the worker throws an uncaught exception?

level: middleimportance: should knowfreq 45%

answer

  1. the thread dies, not the process
  2. error, then exit
  3. EventEmitter with no listener
  4. a reply that never comes

basics

~20 s

The worker thread is terminated and its Worker object emits 'error' with the exception, then 'exit' with code 1. The main thread keeps running only if something listens for 'error'; with no listener, the error is rethrown there and crashes the process.

solid answer

~40 s

An uncaught exception inside a `worker_threads.Worker` terminates that thread only. Node serialises the error back to the parent, where the `Worker` object emits `'error'` with it and then `'exit'` with code 1; messages the worker posted before failing are delivered first. Because `Worker` is an `EventEmitter`, an `'error'` event with no listener is thrown on the main thread, so a missing `worker.on('error')` turns one bad task into a crashed process. Under Node's default `--unhandled-rejections=throw` mode, a rejected promise nobody handles inside the worker takes the same path. Code awaiting a reply should also listen for `'exit'`, or a worker that dies without answering leaves the request hanging.

code

javascript · 20 lines
javascript
import { Worker } from 'node:worker_threads';

function runTask(file, input) {
  return new Promise((resolve, reject) => {
    const worker = new Worker(file, { workerData: input });
    worker.once('message', resolve);
    worker.once('error', reject);
    worker.once('exit', (code) => {
      if (code !== 0) reject(new Error(`worker stopped with exit code ${code}`));
    });
  });
}

const failing = new URL('data:text/javascript,throw new TypeError("bad pixel format")');
try {
  await runTask(failing, null);
} catch (err) {
  console.log('caught in main thread:', err.name, err.message);
}
console.log('main thread keeps serving');

go deeper

for a junior

Recall that a crash in a worker thread kills that thread, and that you must listen for the worker's 'error' event.

for a middle

Explain the event order on the parent, error then exit with code 1, and why an unhandled 'error' on an EventEmitter is rethrown on the main thread.

for a senior

Show the production pattern: settle every pending task on 'error' or a non-zero 'exit', replace dead pool workers, and keep signal handling on the main thread.

for a principal

Decide how the service treats worker failures: retry the task, fail the request, or quarantine the input, and how failures are counted and alerted on.

## The failure stays in the thread A `worker_threads.Worker` runs its own event loop on its own thread. When JavaScript in that thread throws and nothing catches it, the documentation for the `'error'` event says: "The `'error'` event is emitted if the worker thread throws an uncaught exception. In that case, the worker is terminated." So the **thread** dies. The **process** does not, because the error never unwinds through the main thread's stack. Node serialises the exception inside the worker, sends it to the parent, and rebuilds it there before emitting it. Anything can be thrown, so the documented type of the event's `err` argument is `any`; if every attempt to serialise the thrown value fails, the parent receives an `ERR_WORKER_UNSERIALIZABLE_ERROR` instead. ## The order of events on the parent side 1. Any messages the worker posted before it failed are emitted as `'message'` events; the docs guarantee that all messages from the worker arrive before `'exit'`. 2. `'error'` fires with the deserialised exception. 3. `'exit'` fires with an exit code. For a terminated worker the code is `1`; for a worker that called `process.exit(n)` it is `n`. `'exit'` is always the last event a `Worker` emits. ## The listener you must not forget `Worker` extends `EventEmitter`, and the `node:events` documentation states that when an `EventEmitter` has no listener for `'error'` and one is emitted, the error is thrown. That throw happens on the **main thread**, from Node's internals, so it reaches the main thread's `process.on('uncaughtException')` handling and, with no handler, crashes the whole process. The sequence is easy to miss in testing: the worker fails, the parent has no `worker.on('error')`, and a single malformed input file brings down every request the process was serving. | Situation inside the worker | What the parent sees | Main thread | |---|---|---| | Uncaught `throw`, parent has an `'error'` listener | `'error'`, then `'exit'` with 1 | Keeps running | | Uncaught `throw`, no `'error'` listener | Error rethrown on the main thread | Crashes unless handled | | Unhandled rejection under the default `throw` mode | Same as an uncaught `throw` | Depends on the listener | | Worker calls `process.exit(3)` | `'exit'` with 3, no `'error'` | Keeps running | | Parent calls `worker.terminate()` | `'exit'` with 1 | Keeps running | ## Other differences inside a worker The worker environment is close to the main thread, but the failure-related APIs differ in ways that matter: - `process.exit()` inside a worker stops **only that thread**, and `process.abort()` is not available. - Signals are not delivered to the worker through `process.on('SIGTERM')` and friends; the main thread owns signal handling and shutdown. - `--unhandled-rejections=throw` is Node's default mode, so an unhandled rejection is raised as an uncaught exception, and inside a worker that means termination plus an `'error'` event. - Execution can stop at any point when the parent calls `worker.terminate()`, which returns a promise for the exit code. ## Turning this into a safe call The pattern from the Node documentation wraps a worker in a promise that settles on whichever comes first: - `'message'` resolves with the result; - `'error'` rejects with the worker's exception; - `'exit'` with a non-zero code rejects as well, covering a worker that stopped without producing an error, for example one stopped by `worker.terminate()` or one that called `process.exit()` with a non-zero code. Listening for `'exit'` is not redundant. A long-lived worker in a pool that receives a task and then exits without answering would otherwise leave the caller awaiting a reply forever. A pool should also replace a dead worker, so one failure does not shrink capacity permanently. In a pool the same three events drive the bookkeeping. On `'message'` the pool resolves the task the worker was running and marks the worker free. On `'error'` it rejects that task with the worker's exception. On `'exit'` it removes the worker from its lists and, unless the pool is shutting down, starts a replacement. Register these listeners when the worker is created, before the first task is posted, so no failure can arrive while nobody is listening. ## What to say in an interview - The thread dies; the process survives **if** the parent listens for `'error'`. - `'error'` precedes `'exit'`, and earlier messages precede both. - An unhandled rejection in a worker follows the same path under the default mode. - Always handle `'exit'` too, so pending work fails instead of hanging.

  • Why does the runTask pattern listen for 'exit' as well as 'error'?
    Because a worker can stop without an uncaught exception: the parent may call `worker.terminate()`, or the code may call `process.exit()` with a non-zero code. In those cases there is no `'error'` event, only `'exit'`, so a promise waiting on `'message'` and `'error'` alone would never settle and the caller would hang.
  • Can a worker stop its own crash by registering process.on('uncaughtException') inside the worker?
    It can catch the exception there, since the worker has its own `process` event handlers, but the thread then carries on in whatever state the failed code left behind. For a pooled worker that usually means it should report the failure to the parent and exit, letting the pool start a fresh worker, rather than keep serving tasks with a half-updated state.

  • Believing any exception in a worker crashes the whole Node process
  • Believing an exception in a worker is always harmless to the main thread
  • Expecting process.exit() inside a worker to stop the entire program
  • Listening only for 'message' and assuming a reply always arrives
  • Expecting SIGTERM handlers registered in a worker to run on shutdown