liveBook · Manning

Global error handler

As explained in JavaScript in Depth

A top-level error-catching mechanism that receives errors escaping local handlers in a runtime or platform.

An error that escapes its caller

A `try-catch` around `processData()` cannot catch an error thrown later inside its `setTimeout` callback. The caller’s stack has already finished; when the callback runs, the error has no path back to that catch handler. section 7.5

A global error handler is the host runtime’s last resort when an error escapes every available local handler. An uncaught synchronous error can reach it after unwinding the call stack. An error thrown by a later callback can reach it without ever passing through the code that scheduled that callback. section 7.5

The host determines what that last resort looks like:

  • In a browser, an `error` event listener can receive an uncaught error, including one from an asynchronous callback. Its event exposes the error and location fields such as `filename` and `lineno`. section 7.5
  • In Node.js, `process.on('uncaughtException', ...)` receives the error and its origin. An uncaught exception is considered fatal: use the handler for reporting, not for resuming normal operation. Without it, Node.js logs the error and exits. section 7.5
  • Unhandled Promise rejections have distinct hooks: `unhandledRejection` in Node.js and `unhandledrejection` in browsers. section 7.5

Treat global handlers as a safety net for logging and monitoring. They are too far from the failed operation to reliably choose a recovery action; an asynchronous error’s stack trace may also omit the code that scheduled the work. Catch errors at transaction, API, resource, or user-operation boundaries when those boundaries have the context to recover. Frequent arrivals at a global handler point to missing local handling. section 7.5 section 7.6

How JavaScript in Depth covers it

How deep it goes
Explains call-stack escape and asynchronous disconnection, then contrasts browser and Node.js hooks; defers cross-boundary propagation to Promises and async/await.
Examples
Uses a timer callback that evades surrounding try-catch, a browser `error` listener, and a Node.js `uncaughtException` listener.
What it assumes
Assumes familiarity with JavaScript functions, callbacks, and try-catch; explains why scheduling work changes error propagation.
What you can do after
Diagnose/debug with it by reporting escaped errors while moving recovery decisions to handlers with operational context.
How it connects
Connects try-catch, call-stack unwinding, asynchronous callbacks, stack traces, Promise rejections, and semantic error-handling boundaries.

Also explained in

Compare how 2 books explain global error handler →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of JavaScript in Depth. The section links point to the parts of the book it draws on.