Error handling is a crucial aspect in the development of robust and user-friendly web applications. Next.js provides various mechanisms to handle errors effectively and ensure a good user experience even in case of problems.
Next.js automatically creates a default error page that is displayed
when an error occurs. This page can be customized by creating a custom
_error.js
file in the pages
directory.
function Error({ statusCode }) {
return (
<p>
{statusCode
? `An error ${statusCode} has occurred on the server`
: 'An error has occurred on the client'}
</p>
;
)
}
Error.getInitialProps = ({ res, err }) => {
const statusCode = res ? res.statusCode : err ? err.statusCode : 404;
return { statusCode };
;
}
export default Error;
During server-side execution, for example in
getServerSideProps
, errors may occur that should be handled
appropriately. Here you can use try-catch blocks to catch errors and
react accordingly.
export async function getServerSideProps(context) {
try {
// retrieve data
catch (error) {
} // error handling
return { props: { error: 'Error retrieving data' } };
} }
On the client side, errors in React components can be handled using standard JavaScript techniques such as try-catch or error boundary components.
Error Boundaries are React components that catch errors in their child components and display a fallback UI instead of crashing the entire application.
class ErrorBoundary extends React.Component {
constructor(props) {
super(props);
this.state = { hasError: false };
}
static getDerivedStateFromError(error) {
return { hasError: true };
}
render() {
if (this.state.hasError) {
return <h1>An error has occurred</h1>;
}
return this.props.children;
} }
In API routes (pages/api
) you can use Express-like error
handling methods to manage errors. It is advisable to send consistent
error responses to facilitate debugging and error handling on the client
side.
export default function handler(req, res) {
try {
// API logic
catch (error) {
} .status(500).json({ error: 'Internal server error' });
res
} }
Develop a simple Next.js application that makes an API request to an external source (e.g. https://jsonplaceholder.typicode.com/posts) to retrieve data. Implement custom error handling for the following scenarios: 1. server-side error when retrieving the data (e.g. API not reachable). 2. client-side error when displaying the data. 3. a user-defined error page for pages not found (404) and other unexpected errors.
npx create-next-app my-next-project
.2 Creating the pages: In the pages
directory, create an index.js
file for the main page and
_error.js
for the custom error page.
index.js
, use
getServerSideProps
to retrieve data from an external API
and handle possible errors.4 Data display and error handling: Implement logic to display data and catch client-side errors.
5 Custom error page: Create a custom error page in
_error.js
.