Course contentsShow
← Web Development
Lesson 2091 of 2,98238. JavaScript Performance in the BrowserFree lesson

Error Handling in Web Workers

Catching and propagating errors from workers using the error event and proper exception handling patterns.

Error Handling in Web Workers

You'll learn how to catch and handle errors that occur inside Web Workers so your main thread can respond gracefully instead of silently failing.

Why Error Handling Matters in Workers

When code inside a Web Worker throws an error, it doesn't automatically crash your main thread—but it also won't tell you what went wrong unless you explicitly listen for it. Think of a worker like a remote office: if something breaks there, headquarters (your main thread) needs a communication system to know about it.

The error Event

Workers emit an error event when an uncaught exception occurs. You attach a listener to catch these:

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

worker.onerror = function(event) {
  console.error('Worker error:', event.message);
  console.error('File:', event.filename);
  console.error('Line:', event.lineno);
  
  // Prevent the error from propagating to window
  event.preventDefault();
};

The error event object provides message, filename, and lineno properties to help you debug.

Handling Errors Inside the Worker

Inside your worker script, use standard try-catch blocks and communicate errors explicitly via postMessage:

// Inside worker file
self.onmessage = function(e) {
  try {
    const result = riskyCalculation(e.data);
    self.postMessage({ success: true, result });
  } catch (error) {
    self.postMessage({ 
      success: false, 
      error: error.message 
    });
  }
};

This pattern gives you control over error details and lets the main thread decide how to respond—retry, show a user message, or fall back to a different approach.

Key Takeaway: Always listen for the error event on workers for uncaught exceptions, and use try-catch with postMessage inside workers to communicate expected failures back to the main thread with structured error information.