Course contentsShow
← JavaScript
Lesson 2153 of 2,72345. Workers and ConcurrencyFree lesson

Handling Errors in Workers

Understand how to catch and handle errors that occur inside a worker using the error event listener on the Worker instance.

Handling Errors in Workers

You'll learn how to catch and respond to errors that occur inside a Web Worker using the error event listener.

The Challenge with Worker Errors

When code inside a worker throws an error, that error doesn't bubble up to your main thread's try-catch blocks. Workers run in complete isolation, so you need a special mechanism to detect when something goes wrong. Without proper error handling, your worker could fail silently, leaving your application in an unpredictable state.

The error Event Listener

The Worker instance fires an error event whenever an uncaught error occurs inside the worker. You attach a listener just like you would for message events:

const worker = new Worker('worker.js');

worker.addEventListener('error', (event) => {
  console.error('Worker error:', event.message);
  console.error('At line:', event.lineno);
  console.error('In file:', event.filename);
});

The error event object contains useful properties:

  • message: The error message
  • filename: Which file the error occurred in
  • lineno: The line number where it happened

Think of It Like a Smoke Alarm

Imagine a worker as a separate room in your house. If something catches fire (throws an error) in that room, you can't see or smell it from where you are. The error event is like a smoke alarm that alerts you in the main room when something goes wrong in the isolated space.

Graceful Degradation

With error handling in place, you can terminate a failing worker, restart it, or fall back to main-thread processing:

worker.addEventListener('error', (event) => {
  console.warn('Worker failed, terminating...');
  worker.terminate();
  // Optionally handle the task on the main thread instead
});

Key Takeaway: Always attach an error event listener to your Worker instances to catch and handle uncaught errors from the worker thread—these errors won't be caught by main-thread error handling.