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

Error Handling in Cross-Context Messaging

Handle errors when postMessage fails or when transferred objects become unusable.

Error Handling in Cross-Context Messaging

What You'll Learn

You'll learn how to handle failures when postMessage cannot send data and when transferred objects become unusable after transfer.

Why Messaging Can Fail

When you send messages between workers, windows, or threads using postMessage, several things can go wrong. The message might contain unserializable data, a transferred object might be accessed after transfer, or the receiving context might have closed. Unlike synchronous code where errors throw immediately, cross-context messaging errors can be subtle and asynchronous.

Common Failure Scenarios

Unserializable Data: If you try to send a function, DOM node, or other non-cloneable object, postMessage will throw a DataCloneError:

try {
  worker.postMessage({ callback: () => {} }); // Functions can't be cloned
} catch (err) {
  console.error('Failed to send message:', err.name); // DataCloneError
}

Detached Buffers: After transferring an ArrayBuffer, the original becomes unusable (detached). Accessing it throws:

const buffer = new ArrayBuffer(8);
worker.postMessage(buffer, [buffer]); // Transfer ownership

try {
  new Uint8Array(buffer); // Buffer is now detached
} catch (err) {
  console.error('Buffer detached:', err); // TypeError
}

Dead Contexts: Sending to a terminated worker or closed window fails silently or throws depending on timing:

worker.terminate();
try {
  worker.postMessage('hello'); // May throw or fail silently
} catch (err) {
  console.error('Worker already terminated');
}

Defensive Patterns

Always wrap postMessage calls in try-catch blocks and validate data before transfer. Check buffer lengths before using transferred objects, and handle worker error events:

worker.onerror = (err) => {
  console.error('Worker error:', err.message);
};

Key Takeaway:
Wrap postMessage in try-catch blocks to handle serialization failures, never reuse transferred objects, and always monitor worker error events to catch runtime failures in cross-context communication.