Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Error Handling in React 16

Avatar for John Francis John Francis
November 04, 2017

Error Handling in React 16

There is a new component lifecycle method componentDidCatch() in react 16 which will get called when there is an error in child component. This presentation explain how we can use Error Boundary to capture errors

Avatar for John Francis

John Francis

November 04, 2017

More Decks by John Francis

Other Decks in Technology

Transcript

  1. What’s the problem? • White Screen of death ⚰(Error in

    one small component renders a blank page) • Whole React component tree is crashed . • Very difficult to track the issue and debug the code in production
  2. window.onerror • Not supported by all the browsers • Does

    not capture Cryptic “Script error” “Script error” : Happens in Firefox, Safari, and Chrome when an exception violates the browser's same-origin policy - i.e. when the error occurs in a script that's hosted on a domain other than the domain of the current page.
  3. try-catch • It only works with imperative code • Doesn’t

    capture error due to state change in react component
  4. Where to use ErrorBoundary ? • Root Component (must) •

    Main Sections of the page like Header, Footer and Middle Content • Stand alone components like Chat Window, Search Bar • Wherever you suspect that the error might occur The granularity of error boundaries is up to you. You can wrap top level route components, you might also wrap components that might contain obscure code. Its up to you how to best handle protecting against application crashes.
  5. When does error boundary catch errors ? • When there

    is an error in render • In lifecycle methods • In Constructor • Whole tree below them
  6. When does it wont catch ? • Errors in the

    same component • On event handlers unless error is due to state change • Error in try catch block unless error is due to state change • Error in asynchronous code unless error is due to state change • Server side rendering
  7. Error boundaries are a mechanism to prevent React from getting

    into an inconsistent state when it doesn't know what to render due to an error. -Dan Abramov
  8. #11334 - componentDidCatch is not getting called when there is

    an error in promise #11415 - Why are Error Boundaries not triggered for event handlers? #11409 - componentDidCatch not fired as expected More information https://github.com/facebook/react/issues/