Error handling in Next.js allows you to handle and display error states when an error occurs during rendering, data fetching, or API calls. Next.js provides several mechanisms to handle errors effectively. One common approach is to use the ErrorBoundary
component and the getDerivedStateFromError
lifecycle method. Here’s an example:
// components/ErrorBoundary.js
import React from 'react';
class ErrorBoundary extends React.Component {
constructor(props) {
super(props);
this.state = { hasError: false };
}
static getDerivedStateFromError(error) {
// Update state to display error message
return { hasError: true };
}
componentDidCatch(error, errorInfo) {
// Log the error or perform other error handling tasks
console.error('Error caught by ErrorBoundary:', error);
// You can also send error reports to a logging service
// or perform other error tracking actions
}
render() {
if (this.state.hasError) {
// Render error message or fallback UI
return <div>Something went wrong. Please try again later.</div>;
}
// Render children if no error occurred
return this.props.children;
}
}
export default ErrorBoundary;
// pages/social-media-feed.js
import React from 'react';
import ErrorBoundary from '../components/ErrorBoundary';
const SocialMediaFeed = () => {
// Simulated error for demonstration purposes
if (Math.random() < 0.5) {
throw new Error('Error occurred while rendering the social media feed.');
}
return (
<ErrorBoundary>
<div className="social-media-feed">
{/* Render the social media feed */}
</div>
</ErrorBoundary>
);
};
export default SocialMediaFeed;
In this example, the ErrorBoundary
component wraps the SocialMediaFeed
component. If an error occurs during rendering, the getDerivedStateFromError
method in the ErrorBoundary
component is triggered, and the hasError
state is set to true
. This allows you to display an error message or fallback UI within the ErrorBoundary
component.
In the SocialMediaFeed
page, a simulated error is thrown during rendering using Math.random() < 0.5
condition. When this error occurs, it is caught by the ErrorBoundary
component, and the error message “Something went wrong. Please try again later.” is displayed.
You can customize the error handling behavior according to your requirements. For example, you can send error reports to a logging service, redirect users to an error page, or provide additional error details for debugging purposes.