Blog>
Snippets

Error Handling in Data Fetching

Provide an example of a try-catch block in getServerSideProps to handle errors during server-side data fetching, with proper user feedback.
export async function getServerSideProps(context) {
  try {
    // Replace `fetchDataFromAPI` with your actual API fetching logic
    const data = await fetchDataFromAPI();
    return {
      props: { data }, // pass the data to the page component as props
    };
  } catch (error) {
    console.error('Error fetching data:', error);
    return {
      props: {
        error: 'An error occurred while fetching data.'
      }
    };
  }
}
This getServerSideProps function in a Next.js app tries to fetch data from an API. If the fetching fails, it catches the error and logs it to the console while returning an error message in the props to be displayed to the user.
// Inside the React component
if (props.error) {
  return (
    <div className="error-message">
      Error: {props.error}
    </div>
  );
}
// Rest of your component rendering
This is the part of a React component that checks for an error prop. If an error exists, it renders a div with an error message; otherwise, it continues rendering the component normally.
.error-message {
  color: red;
  font-weight: bold;
  margin: 20px;
}
The corresponding CSS for the error message, styling it with red color, bold font, and some margin around it.