Gestione Errori API
L'API restituisce errori in formato JSON consistente.
Formato Errore
json
{
"success": false,
"error": {
"code": "ERROR_CODE",
"message": "Descrizione leggibile",
"details": { ... }
}
}Codici HTTP
| Codice | Significato | Quando |
|---|---|---|
| 200 | OK | Richiesta riuscita |
| 201 | Created | Risorsa creata |
| 204 | No Content | Eliminazione riuscita |
| 400 | Bad Request | Richiesta malformata |
| 401 | Unauthorized | Autenticazione fallita |
| 403 | Forbidden | Permessi insufficienti |
| 404 | Not Found | Risorsa non trovata |
| 422 | Unprocessable | Validazione fallita |
| 429 | Too Many Requests | Rate limit superato |
| 500 | Server Error | Errore interno |
Codici Errore
Autenticazione
| Codice | Descrizione |
|---|---|
UNAUTHORIZED | API Key mancante o non valida |
FORBIDDEN | Permessi insufficienti |
TOKEN_EXPIRED | API Key scaduta |
Validazione
| Codice | Descrizione |
|---|---|
VALIDATION_ERROR | Dati non validi |
MISSING_FIELD | Campo obbligatorio mancante |
INVALID_FORMAT | Formato non corretto |
Risorse
| Codice | Descrizione |
|---|---|
NOT_FOUND | Risorsa non trovata |
ALREADY_EXISTS | Duplicato |
CONFLICT | Conflitto di stato |
Sistema
| Codice | Descrizione |
|---|---|
RATE_LIMIT_EXCEEDED | Troppe richieste |
INTERNAL_ERROR | Errore del server |
Esempi
Validazione
json
{
"success": false,
"error": {
"code": "VALIDATION_ERROR",
"message": "I dati forniti non sono validi",
"details": {
"email": ["Il formato email non è valido"],
"first_name": ["Il campo nome è obbligatorio"]
}
}
}Non Trovato
json
{
"success": false,
"error": {
"code": "NOT_FOUND",
"message": "Contatto con ID 999 non trovato"
}
}Gestire gli Errori
javascript
async function apiCall(url, options) {
const response = await fetch(url, options);
const data = await response.json();
if (!data.success) {
switch (data.error.code) {
case 'UNAUTHORIZED':
// Riautentica
break;
case 'VALIDATION_ERROR':
// Mostra errori di validazione
console.log(data.error.details);
break;
case 'RATE_LIMIT_EXCEEDED':
// Attendi e riprova
break;
default:
// Errore generico
console.error(data.error.message);
}
throw new Error(data.error.message);
}
return data.data;
}TIP
Logga sempre gli errori con il codice completo per facilitare il debug.