# Handle errors and rate limits

Source: https://watership.ca/api-docs/docs/tasks/handle-errors-and-rate-limits

Branch on the problem type, retry only what a retry can fix, wait out a rate limit, and split text that’s too long.

Every error from the API is a problem object ([RFC 9457](https://www.rfc-editor.org/rfc/rfc9457)) with the content type `application/problem+json`. Its `type` field says what went wrong. This guide shows how to decide, for each type, whether to retry, wait, fix the request, or split the text.

## Decide what to do from the type [#decide-what-to-do-from-the-type]

Branch on `type`, not on `title` or `detail`. The type is stable, and the other two are for people and can change.

| `type` ends in | Status | What to do |
|---|---|---|
| `invalid-request` | 400 | Fix the request. The `errors` list names each field. Don't retry. |
| `text-too-long` | 400 | Split the text and check each part. See [Split long text](https://watership.ca/api-docs/docs/tasks/handle-errors-and-rate-limits#split-long-text). |
| `unauthorized` | 401 | Check the key and the `Authorization` header. Don't retry. |
| `not-found` | 404 | The id doesn't exist. Don't retry. |
| `payload-too-large` | 413 | The body is over 1 MiB. Split the text. |
| `unsupported-media-type` | 415 | Send `Content-Type: application/json`. |
| `rate-limited` | 429 | Wait for `Retry-After` seconds, then retry. |
| `internal` | 500 | Retry with backoff, up to a few times. |
| `check-timeout` | 503 | Don't retry the same text. Split it and check each part. |

The [errors reference](https://watership.ca/api-docs/docs/reference/errors) describes each type in full.

## Retry with backoff [#retry-with-backoff]

This function sends a request and retries only the problems a retry can fix: `429` after the time the API asks for, and `500` with exponential backoff and jitter. Every other problem is thrown at once.

```js title="watership-request.mjs"
const API_URL = process.env.WATERSHIP_API_URL ?? 'http://127.0.0.1:4010';
const API_KEY = process.env.WATERSHIP_API_KEY;

export class WatershipProblem extends Error {
  constructor(problem) {
    super(`${problem.title}: ${problem.detail}`);
    this.problem = problem;
    this.type = problem.type.split('/').pop();
  }
}

const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));

export async function request(path, { method = 'GET', body, maxAttempts = 4 } = {}) {
  for (let attempt = 1; ; attempt++) {
    const response = await fetch(`${API_URL}${path}`, {
      method,
      headers: {
        Authorization: `Bearer ${API_KEY}`,
        ...(body ? { 'Content-Type': 'application/json' } : {}),
      },
      body: body ? JSON.stringify(body) : undefined,
    });
    if (response.ok) return response.json();

    const problem = await response.json();
    const retryable = response.status === 429 || response.status === 500;
    if (!retryable || attempt === maxAttempts) throw new WatershipProblem(problem);

    const retryAfter = Number(response.headers.get('Retry-After'));
    const backoff = 2 ** attempt * 500 + Math.random() * 250;
    await sleep(response.status === 429 && retryAfter > 0 ? retryAfter * 1000 : backoff);
  }
}
```

Use it for any endpoint:

```js
import { request, WatershipProblem } from './watership-request.mjs';

try {
  const result = await request('/v1/checks', { method: 'POST', body: { text } });
  console.log(result.counts);
} catch (e) {
  if (e instanceof WatershipProblem && e.type === 'unauthorized') {
    console.error('Check WATERSHIP_API_KEY.');
  } else {
    throw e;
  }
}
```

## Stay under the rate limit [#stay-under-the-rate-limit]

Each key can send 120 requests a minute. Every response says where you stand:

| Header | Meaning |
|---|---|
| `RateLimit-Limit` | Requests allowed per minute |
| `RateLimit-Remaining` | Requests left in this minute |
| `RateLimit-Reset` | Seconds until the count resets |

If you're checking many files, read `RateLimit-Remaining` after each response, and when it reaches zero, wait `RateLimit-Reset` seconds before the next request. That saves a request you know will fail. To check many short texts, combine them into one request where you can. One check of a 20,000-character document is one request. Checking its 50 paragraphs one at a time is 50.

## Split long text [#split-long-text]

A check accepts up to 100,000 characters of text, and a request body up to 1 MiB. To check a longer document, split it at paragraph breaks into parts under the limit, check each part, and add each part's starting line to the line numbers in its findings:

```js
const LIMIT = 100_000;

function split(text) {
  const parts = [];
  let start = 0;
  while (start < text.length) {
    let end = Math.min(start + LIMIT, text.length);
    if (end < text.length) {
      const breakAt = text.lastIndexOf('\n\n', end);
      if (breakAt > start) end = breakAt + 2;
    }
    parts.push({ text: text.slice(start, end), offset: start });
    start = end;
  }
  return parts;
}

const findings = [];
for (const part of split(text)) {
  const lineOffset = text.slice(0, part.offset).split('\n').length - 1;
  const result = await request('/v1/checks', { method: 'POST', body: { text: part.text } });
  for (const f of result.findings) {
    findings.push({ ...f, span: { ...f.span, index: f.span.index + part.offset, line: f.span.line + lineOffset } });
  }
}
```

The same split fixes `check-timeout`, because a shorter text takes less time to check.

## Test your handling against the mock [#test-your-handling-against-the-mock]

The mock never rate-limits or fails on its own. Ask it for an error with the `Prefer` header:

```sh
curl -i http://127.0.0.1:4010/v1/checks \
  -H "Authorization: Bearer wsk_test_example" \
  -H "Content-Type: application/json" \
  -H "Prefer: code=429" \
  -d '{"text": "Hello."}'
```

The response is `429 Too Many Requests` with `Retry-After: 42`. To get the text-too-long problem, send `Prefer: code=400, example=textTooLong`. [Run the mock server](https://watership.ca/api-docs/docs/tasks/run-the-mock-server) lists the options.
