---
title: "Error Responses"
description: "String error codes, reporting all errors at once, and designing an error shape clients can actually use."
---

> Documentation Index
> Fetch the complete documentation index at: https://codex.mirio.dev/llms.txt
> Use this file to discover all available pages before exploring further.

# Error Responses

Error design (string codes, all-at-once reporting, field pointers) applies
regardless of whether your API uses a response envelope. These patterns describe
the error object itself. If you're using an envelope, this object lives under the
`error` key; if you're not, it's the response body directly.

## Error codes are string identifiers

Use `SCREAMING_SNAKE_CASE` strings, not integers:

```http
HTTP/1.1 422 Unprocessable Entity
Content-Type: application/json

{
  "code": "VALIDATION_ERROR",
  "message": "The request body contains invalid fields."
}
```

Not:

```http
HTTP/1.1 422 Unprocessable Entity
Content-Type: application/json

{
  "code": 1042,
  "message": "The request body contains invalid fields."
}
```

Numeric codes seem concise, but they invite numeric reasoning. Clients write range
checks (`code >= 1000 && code < 2000`), treat codes as category prefixes
(`1xxx` = validation, `2xxx` = auth), and eventually the prefix scheme needs a
documentation table to translate numbers back into meaning. That table drifts. The
numbers start meaning different things in different client codebases. You've
reinvented HTTP status codes, but less standardized and scoped only to your API.

String codes are self-documenting. `VALIDATION_ERROR` in a stack trace or a log
tells you what happened without a lookup. They're greppable across every client
codebase that integrates your API. They're also cheap to add without coordination:
`CARD_DECLINED_INSUFFICIENT_FUNDS` can appear next to `CARD_DECLINED` without
needing to reserve a numeric slot in a registry.

**The contract:** `code` is stable; `message` is prose. Clients key on `code`
programmatically: switch statements, error handlers, metric labels. `message` is
for developers reading logs or a response body in a terminal. It can be reworded,
expanded, or translated without breaking any client. Never document the messages as
part of the API contract.

## Error shape

The error object itself, whether it's the whole response body or lives under an
envelope key:

```http
HTTP/1.1 422 Unprocessable Entity
Content-Type: application/json

{
  "code": "VALIDATION_ERROR",
  "message": "The request body contains invalid fields.",
  "details": [
    {
      "code": "REQUIRED",
      "pointer": "/first_name",
      "message": "first_name is required."
    },
    {
      "code": "INVALID_FORMAT",
      "pointer": "/email_address",
      "message": "email_address must be a valid email address."
    },
    {
      "code": "OUT_OF_RANGE",
      "pointer": "/addresses/0/postal_code",
      "message": "postal_code must be 5 digits."
    }
  ]
}
```

| Field               | Description                                      |
| ------------------- | ------------------------------------------------ |
| `code`              | Top-level category: what kind of error this is   |
| `message`           | Human-readable summary for developers            |
| `details`           | Array of specific violations; omitted when empty |
| `details[].code`    | Specific violation type within the category      |
| `details[].pointer` | JSON Pointer (RFC 6901) to the offending field   |
| `details[].message` | What specifically went wrong with that field     |

The top-level `code` and the per-detail `code` serve different consumers.
`VALIDATION_ERROR` is what the client SDK catches to show a form error state.
`REQUIRED` or `INVALID_FORMAT` is what the UI layer reads to decide which message
to render next to which input.

## Report all errors at once

Validate the entire request before responding. If five fields are invalid, return
all five in one response. Returning them one at a time forces clients through a
round-trip per fix: submit, get error, fix field, submit again, get next error.
That's whack-a-mole.

```http
HTTP/1.1 422 Unprocessable Entity
Content-Type: application/json

{
  "code": "VALIDATION_ERROR",
  "message": "The request body contains 3 invalid fields.",
  "details": [
    {
      "code": "REQUIRED",
      "pointer": "/first_name",
      "message": "first_name is required."
    },
    {
      "code": "TOO_LONG",
      "pointer": "/bio",
      "message": "bio must be 500 characters or fewer. Received 1240."
    },
    {
      "code": "INVALID_FORMAT",
      "pointer": "/website_url",
      "message": "website_url must be a valid URL."
    }
  ]
}
```

The client submits once, gets the full picture, and the user can fix everything
in a single edit. This matters most for forms: a user who corrects their email
address shouldn't then discover their password is also invalid.

## Field pointers

Use [JSON Pointer (RFC 6901)](https://www.rfc-editor.org/rfc/rfc6901) syntax for
`pointer`: a `/`-prefixed path from the request body root to the offending value.

```
/email_address          # top-level field
/addresses/0/city       # first item in an array, nested field
/payment/card/number    # deeply nested field
```

The key name `pointer` signals to clients that the value is a path, not a flat
field name. A flat `"field": "email_address"` is fine for simple request shapes
but silently ambiguous when a request has nested objects or arrays. `pointer`
scales to both.

## 400 vs. 422

Use 422 for validation failures: the request was syntactically valid (parseable
JSON, correct Content-Type) but semantically wrong (missing required fields,
values out of range). Use 400 for requests that are malformed at the protocol
level: invalid JSON, wrong Content-Type, missing body.

```http
# 400: unparseable
HTTP/1.1 400 Bad Request
{ "code": "INVALID_JSON", "message": "Request body is not valid JSON." }

# 422: parseable but invalid
HTTP/1.1 422 Unprocessable Entity
{ "code": "VALIDATION_ERROR", "message": "email_address is required." }
```

Many APIs use 400 for both. That's acceptable as long as it's consistent. The
meaningful distinction is in `code`, not the status: a client that handles
`VALIDATION_ERROR` and `INVALID_JSON` differently doesn't care whether both
arrive as 400 or whether they're split across 400 and 422.

## Request-level vs. field-level errors

Not every error has a specific field to point at. Some failures are about the
request as a whole:

```http
HTTP/1.1 409 Conflict
Content-Type: application/json

{
  "code": "DUPLICATE_RESOURCE",
  "message": "A user with this email address already exists."
}
```

No `details` array needed here; the error is the whole point. Reserve `details`
for cases where multiple independent problems can be reported simultaneously.
Adding an empty `details: []` is noise; omit the key when there's nothing in it.

## A stable code vocabulary

Define your codes once and treat them as API surface. A starting set:

| Code                      | Typical status | When to use                                  |
| ------------------------- | -------------- | -------------------------------------------- |
| `VALIDATION_ERROR`        | 422            | Request body or parameter failed validation  |
| `REQUIRED`                | n/a            | detail: field is missing or null             |
| `INVALID_FORMAT`          | n/a            | detail: field doesn't match expected format  |
| `TOO_LONG` / `TOO_SHORT`  | n/a            | detail: length constraint violated           |
| `OUT_OF_RANGE`            | n/a            | detail: numeric value outside allowed bounds |
| `INVALID_VALUE`           | n/a            | detail: value not in the allowed set         |
| `AUTHENTICATION_REQUIRED` | 401            | No credentials provided                      |
| `TOKEN_EXPIRED`           | 401            | Access token has expired                     |
| `TOKEN_INVALID`           | 401            | Token is malformed or signature invalid      |
| `FORBIDDEN`               | 403            | Authenticated but not authorized             |
| `NOT_FOUND`               | 404            | Resource does not exist                      |
| `DUPLICATE_RESOURCE`      | 409            | Unique constraint violated                   |
| `RATE_LIMIT_EXCEEDED`     | 429            | Too many requests                            |
| `INTERNAL_ERROR`          | 500            | Something went wrong on the server           |

Top-level codes (the first column) are what your SDK catches in a `switch` or
`match`. Detail-level codes (`REQUIRED`, `INVALID_FORMAT`, etc.) are what your
UI maps to user-facing messages. Keep the two tiers distinct and the list will
stay manageable.

:::note[Codes are buckets, not labels]
A top-level `code` names a _category_ of failure, not the specific thing that failed.
`NOT_FOUND` is right. `USER_NOT_FOUND`, `ORDER_NOT_FOUND`, and `INVOICE_NOT_FOUND`
are the path to infinite sprawl: a unique code per entity per condition, none of
them reusable, all needing their own entry in every client's error handler.

The `details` array with `pointer` already carries that specificity.
`NOT_FOUND` + `"pointer": "/user_id"` tells the client exactly what wasn't found
without polluting the code namespace. Same goes for validation: `VALIDATION_ERROR`
with a detail of `INVALID_FORMAT` + `"pointer": "/email_address"`, not
`INVALID_USER_EMAIL`.

If you find yourself writing `INVALID_<ENTITY>_<FIELD>`, the detail tier is the
right place for that information.

:::

Adding new codes is always non-breaking. Renaming or removing existing codes
is a breaking change: client handlers stop matching and silently fall through
to their default case.

Source: https://codex.mirio.dev/web/rest-apis/errors/index.mdx
