JavaScript Course
JavaScript
/
Advanced

Global Error Handling

Definition

Mechanism to catch unhandled exceptions and unhandled promise rejections that slip past your local `try/catch` blocks, preventing the application from dying silently.

Explain Like I'm New

Global error handling is the safety net at the very bottom of the circus tent. If the acrobat misses the trapeze (the code fails) and the safety harness snaps (no try/catch), the global error handler catches them before they hit the ground, logs the incident, and politely tells the audience the show is over.

Real World Example

Adding `window.addEventListener('error')` to intercept crashes, sending the stack trace to an external logging service like Sentry or LogRocket, and rendering a fallback 'Something went wrong' UI component.

Common Use Cases

  • •Crash reporting
  • •Fallback UIs (React Error Boundaries)

Interactive Example

Loading...
Console output will appear here...

Interview Questions

basic

  • What happens if you don't catch an error in a JavaScript app?

intermediate

  • What is `unhandledrejection`?

advanced

  • How do Error Boundaries in React relate to global error handling?

Flash Cards

Question

What is unhandledrejection?

Click to reveal answer
Answer

The standard `error` event listener only catches synchronous errors. If a Promise fails (e.g., an API fetch fails) and you forgot to write a `.catch()`, it throws an 'Unhandled Promise Rejection'. You must listen for the `window.addEventListener('unhandledrejection')` event specifically to capture these.

Question

How do React Error Boundaries relate?

Click to reveal answer
Answer

React catches rendering errors internally. A global `window.onerror` will NOT catch an error that happens during a React render cycle. You must use a React `ErrorBoundary` component to catch UI crashes and prevent the entire page from turning into a blank white screen.