Specifieke excepties afvangen en meldingen

Transacties en foutafhandeling in PostgreSQL

Jason Myers

Principal Engineer

Een specifiek type exceptie afvangen

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';
Transacties en foutafhandeling in PostgreSQL

Output van onze exceptiehandler

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)
Transacties en foutafhandeling in PostgreSQL

Veelvoorkomende exceptievoorwaarden

Voorwaarde Voorbeeld
unique_violation Twee dezelfde waarden invoegen in een unieke kolom
not_null_violation Null invoegen in een veld dat geen null toestaat
check_violation Een check constraint schenden, zoals > 11 voor deliciousness
division_by_zero Delen door 0

Veel meer via de link in de bron hieronder

1 https://www.postgresql.org/docs/9.4/errcodes-appendix.html
Transacties en foutafhandeling in PostgreSQL

Meerdere excepties afvangen

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

Transacties en foutafhandeling in PostgreSQL

Meerdere exceptietypen afzonderlijk afvangen

-- Voeg check_violation-exceptie toe
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.';

-- Voeg not_null-exceptie toe
  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';

Transacties en foutafhandeling in PostgreSQL

Output bij meerdere excepties

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)
Transacties en foutafhandeling in PostgreSQL

Tijd om het toe te passen!

Transacties en foutafhandeling in PostgreSQL

Preparing Video For Download...