Domain

ApiError

Struttura errore PostgREST unificata — message, code, details, hint. Formato standard usato dal core (RepositoryUtils) e dal modulo MFE.

Cos'è

ApiError è il formato standard degli errori restituiti da PostgREST. È usato in modo trasversale dal core (RepositoryUtils) e dal modulo @pzeta/postgrest/mfe per normalizzare le risposte di errore della backend prima di ri-lanciarle al consumer.

import type { ApiError } from '@pzeta/postgrest'

Contratto

interface ApiError {
  /** Messaggio di errore principale */
  message: string
  /** Codice errore PostgreSQL (es: '23505' per unique violation) */
  code?: string | undefined
  /** Dettagli aggiuntivi sull'errore */
  details?: string | null | undefined
  /** Suggerimento per risolvere l'errore */
  hint?: string | null | undefined
}

Campi

CampoTipoRequiredDescrizione
messagestringMessaggio principale (sempre presente)
codestringCodice errore PostgreSQL (5 caratteri) — es. 23505 (unique violation), 23503 (foreign key violation), PGRST116 (no rows returned)
detailsstring | nullDettaglio tecnico (es. quale vincolo è stato violato)
hintstring | nullSuggerimento per risolvere (es. "Use UPSERT to handle conflicts")

Codici PostgREST/PostgreSQL più comuni

CodeSignificatoMapping HTTP
23505UNIQUE violation (duplicato)409 Conflict
23503FOREIGN KEY violation409 Conflict
23502NOT NULL violation400 Bad Request
23514CHECK violation400 Bad Request
42501Insufficient privilege401/403
42P01Tabella inesistente404 Not Found
PGRST100Parsing error sulla URL400 Bad Request
PGRST116Nessuna riga (con Accept: application/vnd.pgrst.object+json)406 Not Acceptable
PGRST301JWT scaduto401 Unauthorized
PGRST302JWT non valido401 Unauthorized

Esempio — Error handling

import type { ApiError } from '@pzeta/postgrest'

interface Cliente {
  idcliente: number
  email: string
  pivacf: string
}

try {
  await clientiService.create({ email: 'mario@example.com', pivacf: '12345678901' })
} catch (err) {
  const apiError = err as ApiError

  switch (apiError.code) {
    case '23505':
      showToast(`Cliente già esistente: ${apiError.details ?? apiError.message}`)
      break
    case '23502':
      showToast(`Campo obbligatorio mancante: ${apiError.message}`)
      break
    case 'PGRST301':
      router.push('/login')
      break
    default:
      showToast(apiError.hint ?? apiError.message)
  }
}

Mapping PostgREST → ApiError

PostgREST restituisce errori JSON nel formato:

{
  "code": "23505",
  "details": "Key (email)=(mario@example.com) already exists.",
  "hint": null,
  "message": "duplicate key value violates unique constraint \"clienti_email_key\""
}

RepositoryUtils normalizza questa struttura nel tipo ApiError mantenendo i campi 1:1, garantendo type safety nei catch block.

Nullability: details e hint possono essere null (non solo undefined). Usa controllo apiError.details != null per coprire entrambi i casi quando estrai stringhe.

Tipi correlati

  • AuthError — variante per errori di autenticazione (con timestamp)
  • ICrudRepository — i suoi metodi rilanciano ApiError su fallimento
  • ILogger — usato internamente per loggare errori prima del rethrow