Migliorare la gestione delle eccezioni con le diagnosi impilate

Transazioni e gestione degli errori in PostgreSQL

Jason Myers

Principal Engineer

Catturare più informazioni sull'errore

DO $$
BEGIN
   UPDATE inventory SET cost = 35.0 WHERE name = 'Macaron';
   UPDATE inventory SET cost = 3.50 WHERE name = 'Panellets';
EXCEPTION
   WHEN others THEN
       INSERT INTO errors (msg) VALUES ('Max cost is 10!');
       RAISE INFO 'Max cost is 10!';
END; 
$$ language 'plpgsql';
Transazioni e gestione degli errori in PostgreSQL

Usare le diagnosi impilate

DO $$
DECLARE
   exc_message text;
   exc_detail text;

BEGIN UPDATE inventory SET cost = 35.0 WHERE name = 'Macaron'; UPDATE inventory SET cost = 3.50 WHERE name = 'Panellets';
EXCEPTION WHEN others THEN GET STACKED DIAGNOSTICS exc_message = MESSAGE_TEXT, exc_detail = PG_EXCEPTION_DETAIL; INSERT INTO errors (msg, detail) VALUES (exc_message, exc_detail); RAISE INFO 'Exception Messaage: % | Exception Details: %', exc_message, exc_detail; END$$;
Transazioni e gestione degli errori in PostgreSQL

Esempio di output diagnostico

INFO:  Exception Messaage: new row for relation "inventory" violates check constraint 
"cost_check" | Exception Details: Failing row contains (7, 35, Macaron).
DO

postgres=# \x on
Expanded display is on.
postgres=# select msg, detail from errors;
-[ RECORD 1 ]-------------------------------------------------------------------
msg    | new row for relation "inventory" violates check constraint "cost_check"
detail | Failing row contains (7, 35, Macaron).
Transazioni e gestione degli errori in PostgreSQL

Cosa puoi ottenere?

Name Description
RETURNED_SQLSTATE codice di errore SQLSTATE dell'eccezione
COLUMN_NAME nome della colonna collegata all'eccezione
CONSTRAINT_NAME nome del vincolo collegato all'eccezione
MESSAGE_TEXT testo del messaggio principale dell'eccezione
PG_EXCEPTION_DETAIL testo del messaggio di dettaglio dell'eccezione, se presente
1 https://www.postgresql.org/docs/12/plpgsql-control-structures.html
Transazioni e gestione degli errori in PostgreSQL

Altri punti dati diagnostici

Name Description
PG_DATATYPE_NAME nome del tipo di dati collegato all'eccezione
TABLE_NAME nome della tabella collegata all'eccezione
SCHEMA_NAME nome dello schema collegato all'eccezione
PG_EXCEPTION_HINT testo del suggerimento dell'eccezione, se presente
PG_EXCEPTION_CONTEXT righe di testo dello stack di chiamate al momento dell'eccezione
Transazioni e gestione degli errori in PostgreSQL

Passiamo alla pratica !

Transazioni e gestione degli errori in PostgreSQL

Preparing Video For Download...