Skip to content

Instantly share code, notes, and snippets.

@eugene-ilyin
Created January 17, 2020 04:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save eugene-ilyin/27fa8974ac60548ebc32cd4563950d5b to your computer and use it in GitHub Desktop.
Save eugene-ilyin/27fa8974ac60548ebc32cd4563950d5b to your computer and use it in GitHub Desktop.
React boilerplate to catch any error in application
componentDidCatch (error, errorInfo) {
// Log only errors in component tree, which can break the rendering.
// @see https://reactjs.org/docs/error-boundaries.html
if (this.props.logError) {
this.props.logError(error, errorInfo)
}
}
componentDidMount () {
// Development mode - catches any error.
// Production mode - catch errors in event handlers.
// @see https://github.com/facebook/react/issues/12897#issuecomment-410036991
window.onerror = (message, source, lineNumber, colNumber, error) => {
const techInfo = {source, lineNumber, colNumber}
// Error is object.
if (typeof error === 'object' && error.hasBeenLogged === undefined) {
if (this.props.logError) {
this.props.logError(error, techInfo)
}
// For errors in browser events, like click and etc (or maybe other events also) this callback will be fired 2 times
// because of function rethrowCaughtError from the ReactJS.
// Mark error as logged to do not log it again if it will be fired by ReactJS.
error.hasBeenLogged = true
}
// Error is string. Can be logged twice, because we can't use flag "hasBeenLogged".
if (typeof error === 'string') {
if (this.props.logError) {
this.props.logError(new Error(error), techInfo)
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment