Error Boundaries - Creation
- Any component can be a boundary if defines
componentDidCatch
-
componentDidCatch
behaves like JavaScript catch {}
- Only React Class components can be Boundaries
class ErrorBoundary extends React.Component {
constructor(props) {
super(props);
this.state = { hasError: false };
}
componentDidCatch(error, info) {
this.setState({ hasError: true });
logErrorToMyService(error, info);
}
render() {
if (this.state.hasError) {
return <h1>Something went wrong.</h1>;
}
return this.props.children;
}
}
<ErrorBoundary>
<MyWidget />
</ErrorBoundary>
Error Boundaries - componentDidCatch
-
error
is a JavaScript error object
-
info
is a JavaScript object with componentStack
- Holds information about the component stack at the time of error
- Can be used as a top level wrapper, or many small error wrappers
componentDidCatch(error, info) {
/* Example stack information:
in ComponentThatThrows (created by App)
in ErrorBoundary (created by App)
in div (created by App)
in App
*/
logComponentStackToMyService(info.componentStack);
}
CodePen
Error Boundaries - Within Event Handlers
- Event handlers are just normal JavaScript
- Use regular
try/catch
syntax
class MyComponent extends React.Component {
constructor(props) {
super(props);
this.state = { error: null };
}
handleClick = () => {
try {
} catch (error) {
this.setState({ error });
}
}
render() {
if (this.state.error) {
return <h1>Caught an error.</h1>
}
return <div onClick={this.handleClick}>Click Me</div>
}
}