Skip to content

Instantly share code, notes, and snippets.

@Zerg00s
Created June 1, 2020 00:02
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 Zerg00s/cf85160966b9d8105ced878be5ba2c19 to your computer and use it in GitHub Desktop.
Save Zerg00s/cf85160966b9d8105ced878be5ba2c19 to your computer and use it in GitHub Desktop.
React Error Boundaries
import * as React from "react";
export default class ErrorBoundary extends React.Component<any,
{ hasError: boolean; error: any; errorInfo: any }>{
constructor(props) {
super(props);
this.state = { hasError: false, error: "", errorInfo: "" };
}
public componentDidCatch(error: any, errorInfo: any) {
this.setState({
hasError: true,
error,
errorInfo,
});
console.warn(error);
console.info(errorInfo);
}
public render() {
if (this.state.hasError) {
return (
<div style={{
boxShadow: "3px 3px",
border: "1px solid #888",
padding: "10px",
}}>
<h1>Sorry, something went wrong</h1>
<details style={{ whiteSpace: "pre-wrap" }}>
<summary style={{ cursor: "pointer", fontSize: "18px" }}> View error details 🐞 </summary>
<pre>
{this.state.error && this.state.error.toString()}
<br />
{this.state.errorInfo.componentStack}
</pre>
</details>
</div>
);
}
return this.props.children;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment