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

# Tipos de error

> Formato de respuesta y códigos HTTP que devuelve la API

Cada respuesta de RyzeAPI tiene un formato predecible. Comprender este formato es el primer paso para manejar errores de manera robusta en tu código.

## Formato general de respuesta

Todas las respuestas comienzan con el campo `success`, que indica si la operación fue exitosa.

<Tabs>
  <Tab title="Éxito">
    ```json theme={null}
    {
      "success": true,
      "message": "Message sent successfully",
      "status": "sent",
      "data": { "...": "..." }
    }
    ```

    **Campos comunes en respuestas exitosas:**

    | Campo     | Significado                                                        |
    | --------- | ------------------------------------------------------------------ |
    | `success` | Siempre `true` en éxito                                            |
    | `message` | Descripción legible de lo que ocurrió (úsalo solo para log/UI)     |
    | `status`  | Código de negocio cuando aplica (por ejemplo, `sent`, `connected`) |
    | `data`    | Payload útil del endpoint (varía según el caso)                    |
  </Tab>

  <Tab title="Error">
    ```json theme={null}
    {
      "success": false,
      "error": {
        "message": "Instance is not connected to WhatsApp"
      }
    }
    ```

    **Campos en respuestas de error:**

    | Campo           | Significado                    |
    | --------------- | ------------------------------ |
    | `success`       | Siempre `false` en error       |
    | `error.message` | Texto descriptivo del problema |
  </Tab>
</Tabs>

<Warning>
  El envoltorio de error tiene **solo** `success` + `error.message`. No hay un campo numérico `code` ni `errorType`. La diferenciación programática debe hacerse mediante el **status HTTP** combinado con el contenido de `error.message`.
</Warning>

## Códigos HTTP

|  HTTP | Significado           | Cuándo aparece                                                                    |
| :---: | --------------------- | --------------------------------------------------------------------------------- |
| `200` | OK                    | Operación exitosa de lectura/síncrona                                             |
| `201` | Created               | Creación                                                                          |
| `202` | Accepted              | Trabajo asíncrono creado                                                          |
| `400` | Bad Request           | Falla de validación de body/query; instancia desconectada; identificador inválido |
| `401` | Unauthorized          | Token ausente o inválido                                                          |
| `403` | Forbidden             | Token válido pero sin permiso (ownership)                                         |
| `404` | Not Found             | Instancia/grupo/recurso no existe                                                 |
| `409` | Conflict              | Nombre de instancia duplicado; webhook duplicado                                  |
| `429` | Too Many Requests     | Límite de velocidad; throttling de WhatsApp                                       |
| `500` | Internal Server Error | Error interno (DB, cifrado, whatsmeow)                                            |
| `501` | Not Implemented       | Operación no soportada por el whatsmeow embebido                                  |
| `503` | Service Unavailable   | Módulo Chatwoot no habilitado en el servidor; instancia no conectada              |

## Mensajes literales por categoría

La diferenciación granular entre errores se hace a través del texto de `error.message`. A continuación, los mensajes que puedes encontrar.

<AccordionGroup>
  <Accordion title="Autenticación (401)" icon="key">
    | Mensaje                                                             |
    | ------------------------------------------------------------------- |
    | `Missing token in header`                                           |
    | `Missing token in header, Authorization header, or query parameter` |
    | `Missing token`                                                     |
    | `Invalid token`                                                     |
    | `Invalid instance token`                                            |
    | `Invalid account token`                                             |
    | `Unauthenticated`                                                   |
  </Accordion>

  <Accordion title="Ownership (403)" icon="lock">
    | Mensaje                                                     |
    | ----------------------------------------------------------- |
    | `Instance token does not match requested instance`          |
    | `Instance does not belong to this account`                  |
    | `Not authorized to view group requests (must be admin)`     |
    | `Not authorized to perform this action (must be admin)`     |
    | `Not authorized to update this group (must be admin)`       |
    | `Not authorized to reset group invite link (must be admin)` |
    | `Not allowed to join this group`                            |
    | `Not allowed to leave this group`                           |
  </Accordion>

  <Accordion title="Validación (400)" icon="triangle-exclamation">
    | Mensaje                                                                         |
    | ------------------------------------------------------------------------------- |
    | `Instance name is required`                                                     |
    | `Invalid request body`                                                          |
    | `The 'name' field is required`                                                  |
    | `The 'identifier' query parameter is required (...)`                            |
    | `At least one participant is required`                                          |
    | `At least one field must be provided ...`                                       |
    | `At least one privacy setting must be provided`                                 |
    | `group name must be 25 characters or less`                                      |
    | `Community name must be 25 characters or less`                                  |
    | `invalid participant <number>: <reason>`                                        |
    | `invalid group JID <jid>: <reason>`                                             |
    | `invalid community JID <jid>: <reason>`                                         |
    | `Invalid action. Must be one of: add, remove, promote, demote, approve, reject` |
    | `Invalid <field> value: <value>. Valid values: ...`                             |
    | `Invalid duration format`                                                       |
    | `Invalid invite link or code`                                                   |
    | `Invite link has been revoked or expired`                                       |
    | `Number not found or not registered on WhatsApp`                                |
    | `invalid LID format`                                                            |
  </Accordion>

  <Accordion title="Estado de la instancia (400/503)" icon="plug">
    | HTTP | Mensaje                                                        |
    | :--: | -------------------------------------------------------------- |
    |  400 | `Instance is not connected to WhatsApp`                        |
    |  503 | `Instance not connected` (cuando es crítico para la operación) |
  </Accordion>

  <Accordion title="Límite de velocidad (429)" icon="gauge">
    | Mensaje                                                                          |
    | -------------------------------------------------------------------------------- |
    | `Rate limit exceeded`                                                            |
    | `rate limit exceeded (429): wait before creating again` (throttling de WhatsApp) |
  </Accordion>

  <Accordion title="Conflicto (409)" icon="copy">
    | Mensaje                                              |
    | ---------------------------------------------------- |
    | `Instance with this name already exists`             |
    | `webhook limit reached (max 3 enabled per instance)` |
  </Accordion>

  <Accordion title="Integraciones (Chatwoot)" icon="comments">
    | HTTP | Mensaje                                                                                                                 | Causa                                        |
    | :--: | ----------------------------------------------------------------------------------------------------------------------- | -------------------------------------------- |
    |  401 | `Chatwoot rejected the API token - verify chatwootApiToken. Detail: ...`                                                | Token de Chatwoot inválido                   |
    |  403 | `Chatwoot denied the request - verify the API token has admin scope on account <id>. Detail: ...`                       | El token carece de permiso de admin          |
    |  400 | `Chatwoot account or endpoint not found - verify chatwootBaseUrl (...) and chatwootAccountId (...). Detail: ...`        | `account_id` o URL incorrectos               |
    |  400 | `Chatwoot rejected the request as invalid ... Detail: ...`                                                              | Error 422 de Chatwoot                        |
    |  502 | `Chatwoot is unreachable at <url> - verify chatwootBaseUrl and that the host is reachable from the server. Detail: ...` | DNS, conexión rechazada, timeout o 5xx       |
    |  503 | `integration gateway not configured`                                                                                    | Módulo Chatwoot no habilitado en el servidor |

    La causa raíz proveniente de Chatwoot siempre se incluye después de `Detail:` para diagnóstico.
  </Accordion>

  <Accordion title="Funciones no soportadas (501)" icon="ban">
    | Mensaje                                                                                         |
    | ----------------------------------------------------------------------------------------------- |
    | `WhatsApp client does not support newsletter creation (CreateNewsletter not available)`         |
    | `WhatsApp client does not support listing newsletters (GetSubscribedNewsletters not available)` |
    | `WhatsApp client does not support GetNewsletterInfo`                                            |
    | `WhatsApp client does not support GetNewsletterInfoWithInvite`                                  |
    | `WhatsApp client does not support FollowNewsletter`                                             |
    | `WhatsApp client does not support UnfollowNewsletter`                                           |
  </Accordion>
</AccordionGroup>

## Webhooks: errores de entrega

Los webhooks fallidos no devuelven un error síncrono, se persisten en una cola con:

* `status`: `pending` / `delivered` / `failed`
* `attempts`, `max_attempts` (predeterminado 5)
* `last_error`: mensaje completo
* `next_retry_at`: timestamp del próximo reintento

**Backoff exponencial:**

| Intento   | Próximo reintento |
| --------- | ----------------- |
| 1 (falla) | +1s               |
| 2 (falla) | +5s               |
| 3 (falla) | +30s              |
| 4 (falla) | +5min             |
| 5 (falla) | +30min            |
| 6+        | +1h (cap)         |

Después de `max_attempts`, el estado pasa a `failed` y la fila permanece como Dead Letter Queue (auditoría/replay manual). Detalles en [Eventos](/es/api/events/overview).

## Buenas prácticas

<Check>**Siempre verifica `success`** antes de asumir que el contenido es válido.</Check>
<Check>**El status HTTP es la fuente de verdad**, payloads diferentes pueden tener el mismo `error.message`.</Check>
<Check>**Reintenta `429`** con backoff exponencial; respeta el límite global de 100/min.</Check>
<Check>**No reintentes `4xx` en general** (excepto `408`, `429`).</Check>
<Check>**Para `503` en Chatwoot**, reconoce que el módulo Chatwoot no está habilitado en el servidor y deja de reintentar, regístralo para el operador.</Check>

## Errores de validación de schema

Cuando envías un body con formato incorrecto (campo requerido faltante, tipo incompatible, etc.), la API devuelve `400` con un texto descriptivo:

```json theme={null}
{
  "success": false,
  "error": {
    "message": "Invalid request body"
  }
}
```

<Warning>
  No analices el texto de forma fina, valida tu body antes de enviarlo usando los schemas documentados en cada endpoint.
</Warning>

## Siguiente

<CardGroup cols={2}>
  <Card title="Autenticación" icon="key" href="/es/guide/authentication">
    Detalles sobre tokens y ownership.
  </Card>

  <Card title="Límite de velocidad" icon="gauge" href="/es/guide/rate-limit-cors">
    Límites por minuto y cómo reaccionar a 429.
  </Card>
</CardGroup>
