Blog>
Snippets

Customizing Retry Logic Based on Error Status

Demonstrate how to customize React Query's retry logic to perform retries only for specific HTTP status codes, such as network errors (status code 503).
const customRetryLogic = ({ failureCount, error }) => {
  // Check if the error is an instance of an Error
  if (error instanceof Error) {
    // Attempt to parse the error message to get the status code
    const match = error.message.match(/status code (\d+)/i);
    if (match) {
      const statusCode = parseInt(match[1], 10);
      // Only retry for a 503 Service Unavailable error
      return statusCode === 503;
    }
  }
  // Default to not retrying
  return false;
};
This code defines a function named `customRetryLogic` that determines whether a query should be retried based on the HTTP status code found in the error message. It specifically checks for a 503 Service Unavailable status code, allowing retries only for this condition.
const queryOptions = {
  retry: customRetryLogic,
  // Other React Query options here
};
Here the custom retry logic function `customRetryLogic` is applied to a React Query by including it in the query's options object. This ensures that only errors with a 503 status code will trigger a retry, according to the defined behavior.