Error Handling with Error Boundaries

Pascual Vila
Frontend Instructor.
Error Boundaries are React components that catch JavaScript errors in any part of their child component tree, log those errors, and display an alternative UI instead of the blank screen that would result if the application completely crashed. They are a robust way to handle errors in production.
Creating an Error Boundary:
{`import React from 'react';
class ErrorBoundary extends React.Component {
constructor(props) {
super(props);
this.state = { hasError: false };
}
static getDerivedStateFromError(error) {
// Update state so the next render shows the fallback UI.
return { hasError: true };
}
componentDidCatch(error, errorInfo) {
// You can also log the error to an error reporting service
console.error('Error caught by ErrorBoundary:', error, errorInfo);
}
render() {
if (this.state.hasError) {
// You can render any custom fallback UI
return Something went wrong.
;
}
return this.props.children;
}
}
export default ErrorBoundary;`}
Using an Error Boundary:
{`import React from 'react';
import ErrorBoundary from './ErrorBoundary';
function FailingComponent() {
// This component might throw an error at some point
throw new Error('This component failed!');
return Normal Component
;
}
function App() {
return (
The rest of the application continues to work.
);
}
export default App;`}
Error Boundaries only catch errors in rendering, in lifecycle methods, and in constructors of child components. They do not catch errors inside event handlers, asynchronous code, or errors in the Error Boundary itself.