Gestione Errori

Documentazione completa dei codici errore restituiti dall'API UniMsg e come gestirli.

Formato Errore Standard

Tutti gli errori API seguono questo formato:

{
    "success": false,
    "error": {
        "code": "ERROR_CODE",
        "message": "Descrizione leggibile dell'errore",
        "details": {
            "field": "to",
            "reason": "Formato non valido"
        }
    }
}

Errori per Categoria

Autenticazione (401)

CodiceMessaggioSoluzione
UNAUTHORIZEDToken mancanteIncludi header Authorization
INVALID_TOKENToken non validoVerifica il formato del token
TOKEN_EXPIREDToken scadutoRichiedi un nuovo access token
INVALID_CLIENTCredenziali errateVerifica client_id e client_secret

Permessi (403)

CodiceMessaggioSoluzione
INSUFFICIENT_SCOPEScope non autorizzatoRichiedi token con scope necessario
ACCOUNT_SUSPENDEDAccount sospesoContatta il supporto
IP_NOT_ALLOWEDIP non in whitelistConfigura IP whitelist

Validazione (400/422)

CodiceMessaggioSoluzione
INVALID_PHONENumero telefono non validoUsa formato E.164 (+39...)
INVALID_EMAILEmail non validaVerifica formato email
INVALID_SENDERMittente non validoMax 11 caratteri alfanumerici
MESSAGE_TOO_LONGMessaggio troppo lungoMax 1600 caratteri per SMS
MISSING_PARAMETERParametro obbligatorio mancanteIncludi tutti i parametri required
INVALID_TEMPLATETemplate non trovatoVerifica nome template WhatsApp

Crediti (402)

CodiceMessaggioSoluzione
INSUFFICIENT_CREDITSCrediti insufficientiRicarica il tuo account

Risorse (404)

CodiceMessaggioSoluzione
MESSAGE_NOT_FOUNDMessaggio non trovatoVerifica message_id
WEBHOOK_NOT_FOUNDWebhook non trovatoVerifica webhook_id
TEMPLATE_NOT_FOUNDTemplate non trovatoVerifica nome template

Rate Limiting (429)

CodiceMessaggioSoluzione
RATE_LIMITEDTroppe richiesteAttendi e riprova, rispetta i limiti

Gateway (502/503)

CodiceMessaggioSoluzione
GATEWAY_ERRORErrore provider esternoRiprova dopo qualche secondo
GATEWAY_UNAVAILABLEGateway non disponibileRiprova più tardi

Server (500)

CodiceMessaggioSoluzione
INTERNAL_ERRORErrore internoContatta il supporto se persiste

Gestione Errori Best Practices

Esempio PHP

<?php
try {
    $response = $uniMsg->sms()->send([
        'to' => $phone,
        'message' => $text
    ]);

    if ($response['success']) {
        return $response['data']['message_id'];
    }
} catch (UniMsgException $e) {
    switch ($e->getCode()) {
        case 'INSUFFICIENT_CREDITS':
            // Notifica admin per ricarica
            notifyAdmin('Crediti esauriti');
            break;

        case 'INVALID_PHONE':
            // Errore utente, mostra messaggio
            showError('Numero di telefono non valido');
            break;

        case 'RATE_LIMITED':
            // Riprova dopo delay
            sleep(5);
            return $this->retry($phone, $text);

        case 'GATEWAY_ERROR':
        case 'INTERNAL_ERROR':
            // Log e notifica, riprova più tardi
            logError($e);
            throw new TemporaryFailureException();

        default:
            logError($e);
            throw $e;
    }
}

Retry Logic

Per errori temporanei (5xx, GATEWAY_ERROR, RATE_LIMITED), implementa retry con backoff esponenziale:

async function sendWithRetry(data, maxRetries = 3) {
    for (let attempt = 1; attempt <= maxRetries; attempt++) {
        try {
            return await uniMsg.sms.send(data);
        } catch (error) {
            if (attempt === maxRetries) throw error;

            const isRetryable = [
                'GATEWAY_ERROR',
                'INTERNAL_ERROR',
                'RATE_LIMITED'
            ].includes(error.code);

            if (!isRetryable) throw error;

            const delay = Math.pow(2, attempt) * 1000; // 2s, 4s, 8s
            await sleep(delay);
        }
    }
}