Gestione specifica delle eccezioni e messaggi

Transazioni e gestione degli errori in PostgreSQL

Jason Myers

Principal Engineer

Catturare un tipo specifico di eccezione

DO $$
BEGIN
    UPDATE inventory SET quantity = quantity - 1 WHERE name in ('flour', 'sugar');
EXCEPTION
    WHEN check_violation THEN
           INSERT INTO errors (msg) VALUES ('Quantity can not be less than 0.');
           RAISE INFO 'Quantity can not be less than 0.';
END; 
$$ language 'plpgsql';
Transazioni e gestione degli errori in PostgreSQL

Output dell'handler di eccezione

INFO:  Quantity can not be less than 0.
DO
postgres=# select * from errors;
 error_id | state |               msg                | detail | context
^---------+-------+----------------------------------+--------+---------
        1 |       | Quantity can not be less than 0. |        |
(1 row)
Transazioni e gestione degli errori in PostgreSQL

Tipi comuni di condizioni di eccezione

Condition Name Example
unique_violation Inserire due volte lo stesso valore in una colonna univoca
not_null_violation Inserire null in un campo che non lo consente
check_violation Violazione di un vincolo CHECK, es. valore di deliciousness > 11
division_by_zero Divisione per 0

Molte altre al link nella citazione sotto

1 https://www.postgresql.org/docs/9.4/errcodes-appendix.html
Transazioni e gestione degli errori in PostgreSQL

Catturare più eccezioni

DO $$
BEGIN
    UPDATE inventory SET quantity = quantity - 6, cost = null 
    WHERE name='oatmeal dark chocolate';

Transazioni e gestione degli errori in PostgreSQL

Catturare più tipi di eccezioni singolarmente

-- Aggiungi eccezione check_violation
EXCEPTION
  WHEN check_violation THEN
     INSERT INTO errors (msg) VALUES ('Quantity can not be less than 0.');
     RAISE INFO 'Quantity can not be less than 0.';

-- Aggiungi eccezione not_null
  WHEN not_null_violation THEN
     INSERT INTO errors (msg) VALUES ('Cost can not be null.');
     RAISE INFO 'Cost can not be null.';
END; $$ language 'plpgsql';

Transazioni e gestione degli errori in PostgreSQL

Output con più eccezioni

INFO:  Cost can not be null.
DO
postgres=# select * from errors;
 error_id | state |               msg                | detail | context
^---------+-------+----------------------------------+--------+---------
        2 |       | Cost can not be null.            |        |
(1 row)
Transazioni e gestione degli errori in PostgreSQL

È il momento di applicarlo!

Transazioni e gestione degli errori in PostgreSQL

Preparing Video For Download...