Skip to content

Instantly share code, notes, and snippets.

@jtrein
Created October 27, 2017 10:21
Show Gist options
  • Star 8 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save jtrein/c3936d2dc49f18e5aceae880065ef66e to your computer and use it in GitHub Desktop.
Save jtrein/c3936d2dc49f18e5aceae880065ef66e to your computer and use it in GitHub Desktop.
React Error Boundary Component and HOC
import React, { Component } from 'react';
export default class ErrorBoundary extends Component {
constructor(props) {
super(props);
this.state = { error: null, errorInfo: null };
}
componentDidCatch = (error, errorInfo) => catchFunc(error, errorInfo, this)
render() {
if (this.state.errorInfo) {
return handleError(this)
}
// Normally, just render children
return this.props.children;
}
}
export const withErrorBoundary = WrappedComponent => (
class extends Component {
constructor(props) {
super(props);
this.state = { error: null, errorInfo: null };
}
componentDidCatch = (error, errorInfo) => catchFunc(error, errorInfo, this)
render() {
if (this.state.errorInfo) {
return handleError(this)
}
// Normally, just render children
return <WrappedComponent {...this.props} />;
}
}
);
const catchFunc = (error, errorInfo, ctx) => {
// catch errors in any components below and re-render with error message
ctx.setState({
error: error,
errorInfo: errorInfo
})
// log error messages, etc.
}
const handleError = (ctx) => (
// Error path
<div style={ctx.props.style || styles.error}>
<h2>Something went wrong.</h2>
<details style={{ whiteSpace: 'pre-wrap' }}>
{ctx.state.error && ctx.state.error.toString()}
<br />
{ctx.state.errorInfo.componentStack}
</details>
</div>
);
const styles = {
error: {
backgroundColor: '#f98e7e',
borderTop: '1px solid #777',
borderBottom: '1px solid #777',
padding: '12px',
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment