Skip to content

async/retry: only retry on certain types of errors #6196

Closed

Description

@lionel-rowe

Is your feature request related to a problem? Please describe.

A common use case of async/retry is when fetching data from an API, which has various error scenarios:

  • 5xx error: server-side error, retriable
  • 429 error: too many requests, retriable
  • Other 4xx error: other client-side error, not retriable
  • Various non-HTTP-status errors, pretend they don't exist to simplify this example

Describe the solution you'd like

An option called something like isRetriable that can be provided a callback to check whether to retry a given error.

class HttpError extends Error {
    constructor(public status: number) {
        super()
    }
}

// retry only if the status indicates it's retriable, otherwise reject immediately
const res = await retry(async () => {
    const res = await fetch('https://example.com/api/endpoint')
    if (!res.ok) throw new HttpError(res.status)
    return res
}, {
    isRetriable: (e) => e instanceof HttpError && (e.status === 429 || e.status >= 500),
})

Describe alternatives you've considered

N/A

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions