Blog>
Snippets

Handling errors in parallel routes

Example of using try/catch block within `Promise.all` to gracefully handle errors from multiple parallel routes without crashing the entire Next.js server.
async function fetchDataFromRoutes(routes) {
  try {
    // Wrap each fetch with a promise that resolves even if an error occurs
    const fetchPromises = routes.map(route =>
      fetch(route)
        .then(response => response.json())
        .catch(error => ({ error })) // Catch errors per route and return an object with error info
    );

    // Use Promise.all to execute fetches in parallel
    const results = await Promise.all(fetchPromises);

    // Handle the results, separating successful data from errors
    const { data, errors } = results.reduce((acc, result) => {
      if (result.error) {
        acc.errors.push(result.error);
      } else {
        acc.data.push(result);
      }
      return acc;
    }, { data: [], errors: [] });

    // Return or process the results and errors as needed
    return { data, errors };
  } catch (error) {
    // Handle any unexpected errors that occurred in processing
    throw new Error('Error in handling parallel routes:', error);
  }
}
This function fetchDataFromRoutes accepts an array of route URLs and fetches data from them in parallel using Promise.all. Individual fetch calls are wrapped with a catch to ensure that if one fails, it doesn't affect the others. The results are processed to separate successful data from any errors that occurred. If there's an unexpected error in processing the result, it's caught and can be handled or reported.