Skip to content

Instantly share code, notes, and snippets.

@MrLeebo
Created January 17, 2020 21:51
Show Gist options
  • Save MrLeebo/0254f2752c1d5d395149366b91faf84f to your computer and use it in GitHub Desktop.
Save MrLeebo/0254f2752c1d5d395149366b91faf84f to your computer and use it in GitHub Desktop.
<App>
<ErrorBoundary>
<Routes />
</ErrorBoundary>
</App>
import React from "react";
// Catches rendering errors in child components and shows a generic error alert.
// This is sort of the on "unhandledException" of React, ideally the component would
// handle its own errors, but if that didn't happen then this will prevent the entire
// app from entering an invalid state.
export default class ErrorBoundary extends React.Component {
state = { error: null };
static getDerivedStateFromError(error) {
return { error };
}
render() {
const { error } = this.state;
if (error) {
return (
<div>
<p>Something went wrong.</p>
<p>{error.message}</p>
<button onClick={() => this.setState({ error: null })}>Close</button>
</div>
);
}
return this.props.children;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment