# Errors

Every error has one shape: an RFC 9457 problem document with a stable `code`. Branch on the code, never on the text.

## The problem shape

Every answer that is not `2xx` has the content type `application/problem+json`.

*422 Unprocessable Content*

```json
{
  "type": "https://youniton.example/problems/validation.failed",
  "title": "The request is not valid.",
  "status": 422,
  "detail": "Two fields need attention.",
  "instance": "urn:kanso:request:0192f1b2-55aa-7c21-8d0e-1f3a9b6c2d40",
  "code": "validation.failed",
  "traceId": "4bf92f3577b34da6a3ce929d0e0e4736",
  "errors": [
    { "pointer": "/title", "code": "ticket.title_too_long", "detail": "Use at most 200 characters." },
    { "parameter": "filter[stageId]", "code": "query.invalid", "detail": "This stage is not on the board." }
  ]
}
```

| Member | Meaning |
|---|---|
| `code` | The stable machine code, `<area>.<reason>` in snake_case. Your code branches on it. |
| `status` | The HTTP status again. |
| `title`, `detail` | Text for people. `title` is fixed per code. `detail` follows `Accept-Language` (English, Lithuanian, German). Do not parse it. |
| `instance` | The URN of your request. It equals the `X-Request-Id` header. Give it to support. |
| `traceId` | The trace id, for support. |
| `errors[]` | For `422` and query errors: one entry per problem, with a `pointer` (a JSON Pointer into your body), a `parameter` or a `header`, and its own `code`. |
| extensions | Some codes add members: `currentVersion` (`stale-version`), `capability` (`access.forbidden`), `dimension`, `used`, `max` (`limit.reached`), `limiter` (`rate_limit.exceeded`), `reason`, `ability`. |

A problem never holds a stack trace, SQL or anything that tells you that a hidden record exists.

## Common status codes

| Status | Code | What to do |
|---|---|---|
| 400 | `request.malformed` · `query.invalid` · `query.cursor_invalid` · `idempotency.key_required` | Fix the request. A cursor is bound to its filters; start again without it. |
| 401 | `auth.unauthenticated` | The token is wrong, expired or revoked. Stop and get a new token. |
| 403 | `access.forbidden` (with `capability`) | You can see the record, but you may not do this action. |
| 403 | `service_token.not_allowed_here` | Use the right kind of token for this operation. |
| 403 | `help_desk.ability_missing` (with `ability`) · `help_desk.connection_paused` | The help-desk connection does not have the ability, or an Admin paused it. |
| 403 | `feature.unavailable` (with `reason`) · `tenant.suspended` | The feature is off for the tenant, or the tenant is suspended. |
| 404 | `<entity>.not_found` · `route.not_found` · `tenant.not_found` | The record does not exist, or you cannot see it. Youniton gives the same answer for both. |
| 409 | `<aggregate>.invalid_state` · `limit.reached` · `idempotency.in_flight` | Read the record again. For `idempotency.in_flight`, wait for `Retry-After` and retry with the same key. |
| 412 | `stale-version` (with `currentVersion`) | Someone changed the record. Read it again and apply your change to the new version. |
| 413 | `request.too_large` | Send a smaller body. JSON bodies are at most 1 MiB (2 MiB with a rich-text document). |
| 422 | `validation.failed` · `idempotency.key_reused` | Fix the fields in `errors[]`. Use a new key for a different request. |
| 428 | `precondition.required` | Send `If-Match` with the version. |
| 429 | `rate_limit.exceeded` (with `limiter`) | Wait for the seconds in `Retry-After`, then retry. |
| 500 | `server.error` | Retry later with the same `Idempotency-Key`. Give the `instance` to support. |
| 503 | `service.unavailable` | Wait for `Retry-After`, then retry. |

## Why a hidden record answers 404

A `403` would tell you that a record exists. So a record that you may not see answers `404`, the same as a missing record, in status, body and time. `403` is only for a record that you can see but may not change.

## Codes of the modules

Each module adds its own codes. Some examples:

| Status | Code | When |
|---|---|---|
| 403 | `help_desk.ability_missing` | the help-desk connection does not have the ability of the operation |
| 409 | `help_desk_request.external_reference_exists` (with `requestKey`) | a create with a known external reference and another body |
| 409 | `help_desk_request.closed_for_messages` | a reply on a request that takes no more messages |
| 409 | `file.not_ready` · `file.intent_expired` · `file.too_many_open_intents` | a file is still in its scan; an upload intent is older than one hour; too many open uploads |
| 422 | `file.type_not_accepted` · `file.too_large` | the file type is not on the accept list, or the file is too large |
| 409 | `memory.path_taken` · `memory.directory_not_empty` | an entry already has the path; a directory still holds entries |
| 422 | `memory.path_invalid` · `memory.body_too_large` | the path breaks the path rules; the Markdown body is too large |
| 422 | `spending.category_unknown` | the spending category is not an active category of the tenant |
| 422 | `token.expiry_exceeds_policy` | a token expiry above the tenant's maximum |

The reference lists the statuses of each operation. The specification of each feature lists its codes.

## Handle errors in code

*Branch on problem.code*

**JavaScript**

```js
const res = await fetch(url, options);
if (!res.ok) {
  const problem = await res.json(); // application/problem+json
  switch (problem.code) {
    case "rate_limit.exceeded":
      await sleep(Number(res.headers.get("Retry-After")) * 1000);
      return retry();
    case "stale-version":
      return reloadAndReapply(problem.currentVersion);
    default:
      throw new Error(`${problem.code} (${problem.instance})`);
  }
}
```

**Python**

```python
res = requests.request(method, url, **kwargs)
if not res.ok:
    problem = res.json()
    if problem["code"] == "rate_limit.exceeded":
        time.sleep(int(res.headers["Retry-After"]))
        return retry()
    raise RuntimeError(f"{problem['code']} ({problem['instance']})")
```

**PHP**

```php
try {
    $res = $client->request($method, $url, $options);
} catch (GuzzleHttp\Exception\ClientException $e) {
    $problem = json_decode((string) $e->getResponse()->getBody(), true);
    if ($problem['code'] === 'rate_limit.exceeded') {
        sleep((int) $e->getResponse()->getHeaderLine('Retry-After'));
        return retry();
    }
    throw new RuntimeException($problem['code'] . ' (' . $problem['instance'] . ')');
}
```
