> ## 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 erro

> Formato das respostas e códigos HTTP que a API retorna

Toda resposta da RyzeAPI tem um formato previsível. Entender esse formato é o primeiro passo para tratar erros com robustez no seu código.

## Formato geral das respostas

Todas começam com o campo `success`, que indica se a operação deu certo.

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

    **Campos comuns em respostas de sucesso:**

    | Campo     | Significado                                                   |
    | --------- | ------------------------------------------------------------- |
    | `success` | Sempre `true` em sucesso                                      |
    | `message` | Descrição legível do que aconteceu (use só para log/UI)       |
    | `status`  | Código de negócio quando aplicável (ex.: `sent`, `connected`) |
    | `data`    | Payload útil do endpoint (varia conforme o caso)              |
  </Tab>

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

    **Campos da resposta de erro:**

    | Campo           | Significado                  |
    | --------------- | ---------------------------- |
    | `success`       | Sempre `false` em erro       |
    | `error.message` | Texto descritivo do problema |
  </Tab>
</Tabs>

<Warning>
  O envelope de erro tem **apenas** `success` + `error.message`. Não existe campo `code` numérico nem `errorType`. A diferenciação programática deve ser feita pelo **status HTTP** combinado com o conteúdo de `error.message`.
</Warning>

## Códigos HTTP

|  HTTP | Significado           | Quando aparece                                                                 |
| :---: | --------------------- | ------------------------------------------------------------------------------ |
| `200` | OK                    | Sucesso de leitura/operação síncrona                                           |
| `201` | Created               | Criação                                                                        |
| `202` | Accepted              | Job assíncrono criado                                                          |
| `400` | Bad Request           | Validação de body/query falhou; instância desconectada; identificador inválido |
| `401` | Unauthorized          | Token ausente ou inválido                                                      |
| `403` | Forbidden             | Token válido mas sem permissão (ownership)                                     |
| `404` | Not Found             | Instância/grupo/recurso não existe                                             |
| `409` | Conflict              | Nome duplicado de instância; webhook duplicado                                 |
| `429` | Too Many Requests     | Rate limit; throttling do WhatsApp                                             |
| `500` | Internal Server Error | Erro interno (DB, encryption, whatsmeow)                                       |
| `501` | Not Implemented       | Operação não suportada pelo whatsmeow embarcado                                |
| `503` | Service Unavailable   | Módulo Chatwoot não habilitado no servidor; instância não conectada            |

## Mensagens literais por categoria

A diferenciação fina entre erros é feita pelo texto de `error.message`. Abaixo, as mensagens que você pode encontrar.

<AccordionGroup>
  <Accordion title="Autenticação (401)" icon="key">
    | Mensagem                                                            |
    | ------------------------------------------------------------------- |
    | `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">
    | Mensagem                                                    |
    | ----------------------------------------------------------- |
    | `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="Validação (400)" icon="triangle-exclamation">
    | Mensagem                                                                        |
    | ------------------------------------------------------------------------------- |
    | `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 da instância (400/503)" icon="plug">
    | HTTP | Mensagem                                                  |
    | :--: | --------------------------------------------------------- |
    |  400 | `Instance is not connected to WhatsApp`                   |
    |  503 | `Instance not connected` (quando crítica para a operação) |
  </Accordion>

  <Accordion title="Rate limit (429)" icon="gauge">
    | Mensagem                                                                         |
    | -------------------------------------------------------------------------------- |
    | `Rate limit exceeded`                                                            |
    | `rate limit exceeded (429): wait before creating again` (throttling do WhatsApp) |
  </Accordion>

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

  <Accordion title="Integrações (Chatwoot)" icon="comments">
    | HTTP | Mensagem                                                                                                                | Causa                                      |
    | :--: | ----------------------------------------------------------------------------------------------------------------------- | ------------------------------------------ |
    |  401 | `Chatwoot rejected the API token - verify chatwootApiToken. Detail: ...`                                                | Token Chatwoot inválido                    |
    |  403 | `Chatwoot denied the request - verify the API token has admin scope on account <id>. Detail: ...`                       | Token sem permissão de admin               |
    |  400 | `Chatwoot account or endpoint not found - verify chatwootBaseUrl (...) and chatwootAccountId (...). Detail: ...`        | `account_id` ou URL incorretos             |
    |  400 | `Chatwoot rejected the request as invalid ... Detail: ...`                                                              | Erro 422 do Chatwoot                       |
    |  502 | `Chatwoot is unreachable at <url> - verify chatwootBaseUrl and that the host is reachable from the server. Detail: ...` | DNS, refused, timeout, ou 5xx              |
    |  503 | `integration gateway not configured`                                                                                    | Módulo Chatwoot não habilitado no servidor |

    A causa-raiz vinda do Chatwoot é incluída sempre após `Detail:` para diagnóstico.
  </Accordion>

  <Accordion title="Recursos não suportados (501)" icon="ban">
    | Mensagem                                                                                        |
    | ----------------------------------------------------------------------------------------------- |
    | `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: erros de entrega

Webhooks falhos não retornam erro síncrono, são persistidos numa fila com:

* `status`: `pending` / `delivered` / `failed`
* `attempts`, `max_attempts` (default 5)
* `last_error`: mensagem completa
* `next_retry_at`: timestamp do próximo retry

**Backoff exponencial:**

| Tentativa | Próximo retry |
| --------- | ------------- |
| 1 (fail)  | +1s           |
| 2 (fail)  | +5s           |
| 3 (fail)  | +30s          |
| 4 (fail)  | +5min         |
| 5 (fail)  | +30min        |
| 6+        | +1h (cap)     |

Após `max_attempts`, status vira `failed` e a row permanece como Dead Letter Queue (auditoria/manual replay). Detalhes em [Eventos](/pt/api/events/overview).

## Boas práticas

<Check>**Sempre cheque `success`** antes de assumir que o conteúdo é válido.</Check>
<Check>**Status HTTP é fonte de verdade**, diferentes payloads podem ter o mesmo `error.message`.</Check>
<Check>**Retentar `429`** com backoff exponencial; respeite o limite global de 100/min.</Check>
<Check>**Não retentar `4xx` em geral** (exceto `408`, `429`).</Check>
<Check>**Para `503` no Chatwoot**, entenda que o módulo Chatwoot não está habilitado no servidor e pare tentativas, logue para o operador.</Check>

## Erros de validação de schema

Quando você manda um body com formato errado (falta campo obrigatório, tipo incompatível, etc.), a API retorna `400` com texto descritivo:

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

<Warning>
  Não faça parsing fino do texto, valide seu body antes de enviar usando os schemas documentados em cada endpoint.
</Warning>

## Próximo

<CardGroup cols={2}>
  <Card title="Autenticação" icon="key" href="/pt/guide/authentication">
    Detalhes sobre tokens e ownership.
  </Card>

  <Card title="Rate limit" icon="gauge" href="/pt/guide/rate-limit-cors">
    Limites por minuto e como reagir ao 429.
  </Card>
</CardGroup>
