Best Practices for Handling Errors in Prismic Queries

Hi,
How should I handle errors in Prismic? Should I use a try-catch block when querying documents from the Prismic server via the client instance? If so, is it possible to access the error codes returned from a failed Prismic query?

Thank you!

Yes, handling errors with a try-catch block is a good approach when querying documents from Prismic, as it allows you to catch any issues that may arise and handle them gracefully, especially in cases of network issues or unexpected responses.

Here are those error codes:

When you use Prismic’s client instance to query documents, the client will throw errors that can be caught in a try-catch block. Prismic’s errors often come with additional information, such as HTTP status codes, that can help you understand the nature of the issue. Here’s how to handle it:

Example with try-catch

import * as prismic from '@prismicio/client';

const client = prismic.createClient('<your-repo-name>');

async function fetchDocuments() {
  try {
    const response = await client.getByType('page');
    return response;
  } catch (error) {
    handlePrismicError(error);
  }
}

function handlePrismicError(error) {
  if (error.response && error.response.status) {
    // You can access the HTTP status code here
    const statusCode = error.response.status;
    console.error(`Error: ${statusCode}`);

    switch (statusCode) {
      case 404:
        console.error('Document not found.');
        break;
      case 401:
        console.error('Unauthorized - check your Prismic credentials.');
        break;
      case 500:
        console.error('Internal Server Error - try again later.');
        break;
      default:
        console.error('An unexpected error occurred:', error.message);
    }
  } else {
    // Handle other types of errors (network issues, etc.)
    console.error('An error occurred:', error.message);
  }
}

Key Points

  • Access Error Codes: You can access error.response.status for the HTTP status code, which Prismic will send in most cases.
  • Error Types: Typical HTTP error codes include:
  • 404: The document or endpoint does not exist.
  • 401: Unauthorized, often due to an incorrect access token.
  • 500: Server error, which might be temporary.
  • Network or Unexpected Errors: If the error is due to a network issue or other unexpected error, error.message will usually have the relevant message.

This setup gives you flexibility in handling different error types and customizing your responses based on the error codes returned.

Or how we handle it more simply in our Next.js examples:

Thanks a lot