Skip to main content

Error Boundaries

It catch JavaScript errors anywhere in their child component tree, log those errors, and display a fallback UI instead of the component tree that crashed.

use

  • It's a Class-Based Component which can be used to wrap your application.
  • Catch 404s on our API if someone give it an invalid ID!
  • Now anything that is a child of this component will have errors caught here. Think of this like a catch block from try/catch.
  • A static method is one that can be called on the constructor. You'd call this method like this: ErrorBoundary.getDerivedStateFromError(error). This method must be static.
  • If you want to call an error logging service, componentDidCatch would be an amazing place to do that. I can recommend Sentry and TrackJS.

Create a file at root of the project:

/ErrorBoundary.jsx
import { Component } from "react";
import { Link } from "react-router-dom";

class ErrorBoundary extends Component {
state = { hasError: false };
static getDerivedStateFromError() {
return { hasError: true };
}
componentDidCatch(error, info) {
console.error("ErrorBoundary caught an error", error, info);
}
render() {
if (this.state.hasError) {
return (
<h2>
There was an error with this listing. <Link to="/">Click here</Link>{" "}
to back to the home page.
</h2>
);
}

return this.props.children;
}
}

export default ErrorBoundary;