Handle 429 errors correctly in Typescript using got: an example

This assumes Typescript, and using the got library:

import got from "got";

And now on how to handle the request gracefully:

const getCompletion = async (url: string): Promise<ReturnedDataType> => {
  const response = (await got
    .get(url, {
      retry: {
        limit: 10,
        methods: ["GET"],
        statusCodes: [429],
        calculateDelay: ({ computedValue }) => {
          const delay =
            computedValue + Math.random() * 1000 || 100 + Math.random() * 10000;
          console.log(`Retrying fetching completion for ${url} in ${delay}, ms`);
          return delay;
    .json()) as ReturnedDataType;

  return response;
1 Like

Careful with spelling :slight_smile:

Thanks for posting your retry method.


1 Like

Thanks for the heads up :slight_smile: I was wondering why i kept getting those squiggly lines! :slight_smile:

Careful with this. OpenAI is charging for tokens in the prompt even when an error occurs.