> ## Documentation Index
> Fetch the complete documentation index at: https://docs.zenrows.com/llms.txt
> Use this file to discover all available pages before exploring further.

> ## Agent Instructions
> The Zenrows HTTP API serves Fetch and Extract (extract=auto) at https://api.zenrows.com/v1/, Crawl at https://api.zenrows.com/v1/crawls, and Batch at https://async.api.zenrows.com/v1. Fetch, Extract, Crawl and Batch are described in OpenAPI 3.1 at https://www.zenrows.com/openapi.json and listed in the RFC 9727 API catalog at https://www.zenrows.com/.well-known/api-catalog. Every endpoint also has its own page under /api-reference with its schema. Use the spec for exact parameter names and types. Crawl's endpoints, parameters and errors are also at https://docs.zenrows.com/crawl/endpoints.md. To call Zenrows from an agent, connect the MCP server at https://mcp.zenrows.com/mcp. To search these docs from an agent, connect the docs MCP server at https://docs.zenrows.com/mcp. Agent skills for Zenrows are published at https://github.com/ZenRows/cli and install with `npx skills add ZenRows/cli`.

# Error Handling and Retries with the Go SDK

> Configure automatic retries in the Zenrows Go SDK and handle its custom error types.

The Go SDK separates two kinds of failure: errors returned before a request is even sent (bad configuration, invalid parameters, malformed URLs), and unsuccessful HTTP responses that still come back as a valid `*Response`. Retries, once you turn them on, apply to the second kind, and to a connection that failed before the request was sent.

## Basic usage

Retries are **off by default** (`maxRetryCount` is `0`): the client sends each request once. Pass `WithMaxRetryCount` to turn them on:

```go theme={null} theme={"theme":"css-variables"}
client := scraperapi.NewClient(
    scraperapi.WithAPIKey("YOUR_ZENROWS_API_KEY"),
    scraperapi.WithMaxRetryCount(3),
)

response, err := client.Get(context.Background(), "https://www.scrapingcourse.com/ecommerce/", nil)
```

With `WithMaxRetryCount(3)`, a failed request is tried up to 4 times in all. The client then returns the last response or error it got.

> [!NOTE]
>
> This retry policy needs Go SDK `service/api` v1.4.0 or later. If you upgrade with a retry count already set, see [Upgrading from earlier versions](#upgrading-from-earlier-versions).

## When to enable retries

Enable retries (2 to 3 is a reasonable starting point) whenever you're running requests at scale or in production, anywhere a transient `429` or `5xx` shouldn't fail your whole job. Leave retries off (the default) for quick one-off scripts or debugging, where you'd rather see the raw failure immediately.

> [!WARNING]
>
> Don't also wrap the client in your own retry loop: the tries multiply. With `WithMaxRetryCount(2)` (3 tries) inside a loop of 4 tries, one call can send up to 12 requests.

## Which failures get retried

With `WithMaxRetryCount` set, the client retries a `GET` (`Get`, `Fetch`, `Extract`, or `Scrape` with `GET`) after:

1. A `429`, `500`, `502`, `503` or `504`.
2. A `422`, except Extract's `422` with code `no_data_extracted`, which is a final answer.
3. A failure to connect: a refused connection, a name that did not resolve, an unreachable network, or a connect timeout. The request never reached the API.

It never retries:

1. A `POST` or `PUT`, whatever its headers, or a `GET` whose body is an `io.Reader`. An `Idempotency-Key` header in `RequestParameters.CustomHeaders` is forwarded to the target site and does not change this.
2. Any other network error, such as a read timeout or a connection reset after the request was sent. The API may still finish that request and charge it.
3. A canceled or expired context.
4. Any other status.
5. A status from the target site: any status when `ReturnOriginalStatus` is set, and a status listed in `AllowedStatusCodes`.

To retry a `POST` or `PUT`, write your own retry loop, and only when the target site can safely receive the same request twice.

## How long the SDK waits

1. When the API sends `Retry-After` in whole seconds, the client waits that long, from 250ms to 30 seconds, even above `WithRetryMaxWaitTime`. Any other `Retry-After`, such as a date, is ignored.
2. Otherwise it waits a random time between 250ms and `RetryWaitTime * 2^n`, where `n` is 0 for the first retry, capped at `WithRetryMaxWaitTime`. With the defaults, that is up to 1 second before the first retry, 2 seconds before the second, and so on.
3. A retry starts only if its wait ends within the retry budget (`WithRetryBudget`) of the first attempt. A running attempt is not cut short, so a call can take longer than that.

To stop a call, cancel its context: the wait ends at once and the client sends no further request. While a call waits, it keeps its `WithMaxConcurrentRequests` slot, so other calls on the same client can wait too.

| Option | Default | Description |
| - | - | - |
| `WithMaxRetryCount(n int)` | `0` | Retries after the first attempt. `0` sends each request once |
| `WithRetryWaitTime(d time.Duration)` | `1s` | Base of the random backoff. `0` counts as 250ms |
| `WithRetryMaxWaitTime(d time.Duration)` | `30s` | Longest random wait before a retry |
| `WithRetryBudget(d time.Duration)` | `90s` | Retry budget, counted from the first attempt |

```go theme={null} theme={"theme":"css-variables"}
client := scraperapi.NewClient(
    scraperapi.WithAPIKey("YOUR_ZENROWS_API_KEY"),
    scraperapi.WithMaxRetryCount(5),
    scraperapi.WithRetryWaitTime(2*time.Second),     // the first retry waits up to 2s, the second up to 4s
    scraperapi.WithRetryMaxWaitTime(10*time.Second), // no random wait is longer than 10s
)
```

`WithMaxRetryCount(-1)` makes every call return an `InvalidOptionError` and send no request. With a retry count above 0, so does a negative `WithRetryWaitTime`, or a `WithRetryMaxWaitTime` or `WithRetryBudget` of 0 or less. With no retry count, the other retry options are not checked.

> [!TIP]
>
> You aren't charged for retried attempts that fail. Only successful responses count toward your usage. See the [Retry Failed Requests](https://docs.zenrows.com/academy/retry-failed-requests.md) guide for more on how this works.

## Upgrading from earlier versions

From `service/api` v1.4.0, an existing retry count behaves differently. A client with no retry count is unchanged. If you already set `WithMaxRetryCount`, check these changes:

* A `502`, `503` and `504` are now retried.
* A `POST` or `PUT` is never retried, on any status or error.
* Only a failed connection is retried. A reset or EOF after the request was sent, a read timeout, a TLS error and a proxy error are not.
* A `GET` whose body is an `io.Reader` is no longer retried.
* A status from the target site (`ReturnOriginalStatus`, `AllowedStatusCodes`) is no longer retried.
* `WithRetryWaitTime` is now the base of a random backoff, default `1s`. It was a minimum wait, default `5s`. Every wait is at least 250ms.
* A `Retry-After` from the API sets the wait, up to 30 seconds, even above `WithRetryMaxWaitTime`. No retry starts after 90 seconds.
* An invalid retry option makes every call return an `InvalidOptionError`, and `WithMaxRetryCount(-1)` no longer panics.

## Handling failures

> [tab] HTTP error status
>
> Even after retries are exhausted, the SDK returns a `*Response` with `err == nil`. It doesn't turn a non-2xx status into a Go `error` on its own. Always check the response before trusting its content:
>
> ```go theme={null} theme={"theme":"css-variables"}
> response, err := client.Get(context.Background(), url, nil)
> if err != nil {
>     log.Fatal(err)
> }
>
> if response.IsSuccess() {
>     fmt.Println(response.String())
> } else {
>     fmt.Println("Failed after retries:", response.StatusCode())
>     if prob := response.Problem(); prob != nil {
>         fmt.Println("Detail:", prob.Detail)
>     }
> }
> ```

> [tab] SDK and network errors
>
> The other cases return a non-`nil` `error` instead of a response, before any HTTP call is attempted (except for genuine network failures, which happen mid-request):
>
> ```go theme={null} theme={"theme":"css-variables"}
> response, err := client.Get(ctx, targetURL, params)
> if err != nil {
>     var notConfigured scraperapi.NotConfiguredError
>     var invalidMethod scraperapi.InvalidHTTPMethodError
>     var invalidURL scraperapi.InvalidTargetURLError
>     var invalidParam scraperapi.InvalidParameterError
>     var invalidOption scraperapi.InvalidOptionError
>
>     switch {
>     case errors.As(err, &notConfigured):
>         log.Fatal("missing API key")
>     case errors.As(err, &invalidMethod):
>         log.Fatal("unsupported HTTP method")
>     case errors.As(err, &invalidURL):
>         log.Fatal("bad target URL: ", err)
>     case errors.As(err, &invalidParam):
>         log.Fatal("bad request parameters: ", err)
>     case errors.As(err, &invalidOption):
>         log.Fatal("bad client option: ", err)
>     default:
>         log.Fatal("network or unexpected error: ", err)
>     }
> }
> ```
>
> > [!NOTE]
> >
> > Use `context.WithTimeout(ctx, 3*time.Minute)` if you want a request canceled after a fixed duration. We recommend not going below 3 minutes, since canceling a request client-side doesn't immediately free up the concurrency slot on Zenrows' side.

## The SDK error types

| Error type | When it happens |
| - | - |
| `NotConfiguredError` | No API key was set (neither `WithAPIKey` nor `ZENROWS_API_KEY`). |
| `InvalidHTTPMethodError` | You called `Scrape` with a method other than `GET`, `POST`, or `PUT`. |
| `InvalidTargetURLError` | The target URL is empty or fails to parse; wraps the underlying `url.Parse` error via `Unwrap()`. |
| `InvalidParameterError` | A `RequestParameters` field fails validation, for example, `ScreenshotQuality` outside 1 to 100, or `Screenshot: false` combined with `ScreenshotFullPage: true`. |
| `InvalidOptionError` | The client was created with an invalid retry option, for example `WithMaxRetryCount(-1)`, or `WithRetryBudget(0)` with a retry count above 0. `NewClient` returns no error, so every call returns this one and sends no request. |

All are returned as values (not pointers), and `InvalidTargetURLError` supports `errors.Unwrap` so you can inspect the underlying parse error with `errors.As` or `errors.Is`.

## Troubleshooting

* **Response still fails after retries are exhausted**: Check `response.StatusCode()` and look it up in [API Error Codes](https://docs.zenrows.com/api-error-codes.md). Some failures, like an invalid API key, aren't fixed by retrying.
* **Getting `InvalidParameterError` for a parameter you didn't set**: Several `RequestParameters` fields depend on each other, for example, `ScreenshotFullPage` requires `Screenshot: true`, and `WaitForSelector` requires `JSRender: true`. Check `Validate()`'s rules in the SDK source if the message isn't specific enough.
* **`429` errors even with retries**: You're likely exceeding your plan's concurrency limit, not hitting a one-off rate limit. See [Concurrency](https://docs.zenrows.com/fetch/sdk/go/async-concurrency.md).
* **Retries seem to take a long time**: That's the backoff by design. A `Retry-After` from the API can make a wait up to 30 seconds. Lower `WithMaxRetryCount` or `WithRetryBudget` if latency matters more than success rate.

## Pricing

Retried attempts that fail are **not** billed. Only the final successful response counts:

| Configuration | Credits per request |
| - | - |
| Basic request | 1 |
| `JSRender: true` | 5 |
| `UsePremiumProxies: true` | 10 |
| `JSRender: true` + `UsePremiumProxies: true` | 25 |

> [!NOTE]
>
> `404` and `410` responses count as successful and are billed, since the request itself completed correctly.

## FAQ

> [accordion] What's the default number of retries?
>
> Zero. Retries are off unless you pass `WithMaxRetryCount(n)` with `n > 0`.

> [accordion] Which status codes trigger an automatic retry?
>
> `422` (except `no_data_extracted`), `429`, `500`, `502`, `503` and `504`, plus a connection that failed before the request was sent. A `POST` or `PUT` is sent once and never retried.

> [accordion] Does the SDK ever return a Go error for a non-2xx response?
>
> No. A non-2xx HTTP response is still a successful round trip from the SDK's point of view, it returns a `*Response` with `err == nil`. Check `response.IsError()` or `response.StatusCode()` yourself.

## Look up a specific error code

For a full breakdown of Zenrows error codes (like `AUTH002` or `RESP001`) and how to resolve each one, see the [API Error Codes](https://docs.zenrows.com/api-error-codes.md) reference.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.