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

# Gestione Errori & Codici di Risposta

> Guida completa per gestire gli errori API e i codici di risposta

## Introduzione

Questa guida copre tutti i possibili codici di risposta, formati di errore e best practice per gestire gli errori durante l'integrazione con l'API Lovi.

## 📊 Codici di Stato HTTP

### Risposte di Successo

#### 200 OK - Richiesta Riuscita

**Notifica Elaborata:**

```json theme={null}
{
  "success": true,
  "message": "Notifica accodata con successo",
  "notification_id": "uuid-notification-123",
  "scheduled_time": "2024-12-25T10:30:00Z"
}
```

**Template Recuperati:**

```json theme={null}
{
  "templates": [
    {
      "id": "template_001",
      "name": "welcome_user",
      "status": "approved"
    }
  ],
  "total": 1
}
```

**Template Creato:**

```json theme={null}
{
  "success": true,
  "message": "Template creato con successo",
  "template": {
    "id": "new_template_123",
    "name": "order_confirmation",
    "status": "pending"
  }
}
```

***

### Risposte di Errore Client (4xx)

#### 400 Bad Request - Parametri Non Validi

**Campo Richiesto Mancante:**

```json theme={null}
{
  "error": "validation_failed",
  "message": "Campo richiesto mancante",
  "details": {
    "field": "contact.number",
    "reason": "Questo campo è richiesto"
  },
  "request_id": "req_123456789"
}
```

**Formato Parametro Non Valido:**

```json theme={null}
{
  "error": "validation_failed",
  "message": "Formato parametro non valido",
  "details": {
    "field": "datetime_sending",
    "provided": "25-12-2024",
    "expected_format": "ISO 8601 (YYYY-MM-DDTHH:MM:SS)",
    "example": "2024-12-25T10:30:00"
  },
  "request_id": "req_123456790"
}
```

#### 401 Unauthorized - Autenticazione Fallita

**Chiave di Accesso Non Valida:**

```json theme={null}
{
  "error": "unauthorized",
  "message": "Chiave di accesso non valida o scaduta",
  "details": {
    "reason": "La chiave di accesso fornita non è valida o è stata revocata"
  },
  "request_id": "req_123456793"
}
```

#### 403 Forbidden - Accesso Negato

**Permessi Insufficienti:**

```json theme={null}
{
  "error": "forbidden",
  "message": "Permessi insufficienti per questa risorsa",
  "details": {
    "reason": "La tua chiave API non ha il permesso di creare template"
  },
  "request_id": "req_123456795"
}
```

#### 404 Not Found - Risorsa Non Trovata

**Template Non Trovato:**

```json theme={null}
{
  "error": "template_not_found",
  "message": "Template 'welcome_user' non trovato o non approvato",
  "details": {
    "template_name": "welcome_user",
    "language": "it_IT",
    "suggestion": "Controlla il nome del template e lo stato di approvazione"
  },
  "request_id": "req_123456797"
}
```

#### 422 Unprocessable Entity - Errore Logica Business

**Template Non Approvato:**

```json theme={null}
{
  "error": "template_not_approved",
  "message": "Il template non è in stato approvato",
  "details": {
    "template_name": "pending_template",
    "current_status": "pending",
    "required_status": "approved"
  },
  "request_id": "req_123456799"
}
```

#### 429 Too Many Requests - Limite di Tariffa Superato

**Limite di Tariffa Raggiunto:**

```json theme={null}
{
  "error": "rate_limit_exceeded",
  "message": "Troppe richieste. Riprova tra 60 secondi",
  "details": {
    "limit": 100,
    "window": "1 ora",
    "reset_time": "2024-12-20T16:30:00Z"
  },
  "retry_after": 60,
  "request_id": "req_123456801"
}
```

***

### Risposte di Errore Server (5xx)

#### 500 Internal Server Error

**Errore Server Generale:**

```json theme={null}
{
  "error": "internal_error",
  "message": "Si è verificato un errore imprevisto",
  "details": {
    "reason": "Errore interno del server"
  },
  "request_id": "req_123456803"
}
```

#### 502 Bad Gateway

**Errore Servizio Upstream:**

```json theme={null}
{
  "error": "service_unavailable",
  "message": "Servizio WhatsApp temporaneamente non disponibile",
  "details": {
    "service": "whatsapp_gateway",
    "estimated_recovery": "2024-12-20T16:00:00Z"
  },
  "request_id": "req_123456804"
}
```

#### 503 Service Unavailable

**Modalità Manutenzione:**

```json theme={null}
{
  "error": "service_unavailable",
  "message": "Servizio temporaneamente non disponibile per manutenzione",
  "details": {
    "maintenance_window": "2024-12-20T02:00:00Z to 2024-12-20T04:00:00Z"
  },
  "request_id": "req_123456805"
}
```

***

## 🔄 Strategie di Retry

### Logica di Retry Raccomandata

| Codice Stato    | Azione                                  | Strategia di Retry           |
| --------------- | --------------------------------------- | ---------------------------- |
| `400, 404, 422` | ❌ **Non riprovare**                     | Correggi richiesta e riprova |
| `401, 403`      | ❌ **Non riprovare**                     | Aggiorna autenticazione      |
| `429`           | ⏰ **Riprova con backoff**               | Usa header `retry_after`     |
| `500, 502, 503` | 🔄 **Riprova con backoff esponenziale** | Max 3 tentativi              |

***

## 📝 Best Practice

### Checklist Gestione Errori

✅ **Validazione Pre-Richiesta**

* Valida formato numero telefono
* Controlla campi richiesti
* Valida formato datetime
* Verifica esistenza template

✅ **Monitoraggio Richieste**

* Registra tutte le richieste API
* Includi request\_id nei log
* Monitora tempi di risposta
* Traccia tassi di errore

✅ **Recupero Errori**

* Implementa logica di retry appropriata
* Memorizza token di autenticazione
* Gestisci limiti di tariffa con grazia
* Fornisci messaggi di errore significativi agli utenti

✅ **Esperienza Utente**

* Mostra messaggi di errore user-friendly
* Fornisci feedback actionable
* Non esporre dettagli di errore interni
* Offri alternative quando possibile

Ricorda di includere sempre il `request_id` quando contatti il supporto per una risoluzione più veloce dei problemi.
