Skip to main content

Gestione degli errori GraphQL

Due tipi di errore

TipoDove appareQuando si usa
userErrorsNel payload della mutationErrori di validazione e business logic
errors (GraphQL)In cima alla rispostaErrori strutturali, risorsa non trovata, permessi

1. userErrors - errori di validazione

Ogni mutation restituisce un campo userErrors: null se l'operazione riesce, altrimenti la lista degli errori.

Struttura:

type UserError {
  code: ErrorCode!
  field: String       # campo specifico che ha causato l'errore, se applicabile
  message: String     # descrizione leggibile
}

enum ErrorCode {
  BAD_INPUT    # input non valido o mancante
  NOT_FOUND    # risorsa non trovata
  NOT_UNIQUE   # violazione di unicità
  PROTECTED    # eliminazione bloccata da dipendenze
}

Esempio di risposta con errore:

{
  "data": {
    "supporterCreate": {
      "supporter": null,
      "userErrors": [
        {
          "code": "BAD_INPUT",
          "field": "email",
          "message": "This field is required."
        }
      ]
    }
  }
}

Esempio di risposta con successo:

{
  "data": {
    "supporterCreate": {
      "supporter": {
        "id": 42,
        "email": "mario@example.com"
      },
      "userErrors": null
    }
  }
}

Come gestire userErrors

Controlla userErrors prima di usare i dati restituiti:

const { data } = await client.mutate({ mutation: CREATE_SUPPORTER, variables });

if (data.supporterCreate.userErrors?.length) {
  const errors = data.supporterCreate.userErrors;
  // gestisci gli errori per campo
  errors.forEach(err => {
    console.error(`[${err.code}] ${err.field}: ${err.message}`);
  });
  return;
}

const supporter = data.supporterCreate.supporter;

2. Errori GraphQL - eccezioni strutturali

Gli altri errori arrivano nell'array errors della risposta, come errori GraphQL standard.

Casi comuni:

SituazioneTipo di errore
Risorsa non trovata in una queryGraphqlNotFound
Token non valido o mancanteerrore di autenticazione
Permessi insufficientierrore di autorizzazione
Query malformataerrore di parsing

Esempio di risposta:

{
  "data": null,
  "errors": [
    {
      "message": "Resource not found",
      "locations": [{ "line": 2, "column": 3 }],
      "path": ["donation"]
    }
  ]
}

Nota: Lo status HTTP è quasi sempre 200 anche con errori GraphQL: controlla il campo errors.

Come gestire gli errori GraphQL

const response = await client.query({ query: GET_DONATION, variables: { id: 999 } });

if (response.errors?.length) {
  const message = response.errors[0].message;
  // es. "Resource not found"
  console.error('GraphQL error:', message);
  return;
}

Pattern consigliato

async function safeMutate(client, mutation, variables) {
  let response;

  try {
    response = await client.mutate({ mutation, variables });
  } catch (networkError) {
    // Errore di rete o HTTP 5xx
    throw new Error('Network error: ' + networkError.message);
  }

  // Errori strutturali GraphQL
  if (response.errors?.length) {
    throw new Error('GraphQL error: ' + response.errors[0].message);
  }

  // Errori di business logic nella mutation
  const rootKey = Object.keys(response.data)[0];
  const result = response.data[rootKey];

  if (result.userErrors?.length) {
    throw new Error('Validation error: ' + result.userErrors[0].message);
  }

  return result;
}

Fonte: https://dev.riseact.org/docs/apis/graphql-errors. Copia automatica da dev.riseact.org: non modificare qui, le modifiche vanno fatte sulla documentazione Docusaurus.