Obsługa wyjątków i komunikaty błędów

Transakcje i obsługa błędów w PostgreSQL

Jason Myers

Principal Engineer

Przechwytywanie określonego typu wyjątku

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';
Transakcje i obsługa błędów w PostgreSQL

Wynik obsługi wyjątku

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)
Transakcje i obsługa błędów w PostgreSQL

Typowe rodzaje warunków wyjątków

Nazwa warunku Przykład
unique_violation Wstawienie tej samej wartości do kolumny z ograniczeniem unikalności
not_null_violation Wstawienie wartości null do pola niedopuszczającego null
check_violation Naruszenie ograniczenia CHECK, np. wartość wyższa niż 11 w kolumnie deliciousness
division_by_zero Dzielenie przez 0

Więcej warunków pod linkiem w cytowaniu poniżej

1 https://www.postgresql.org/docs/9.4/errcodes-appendix.html
Transakcje i obsługa błędów w PostgreSQL

Przechwytywanie wielu wyjątków

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

Transakcje i obsługa błędów w PostgreSQL

Przechwytywanie wielu typów wyjątków osobno

-- Add check_violation exception
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.';

-- Add non-null exception
  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';

Transakcje i obsługa błędów w PostgreSQL

Wynik przechwytywania wielu wyjątków

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)
Transakcje i obsługa błędów w PostgreSQL

Czas na praktykę!

Transakcje i obsługa błędów w PostgreSQL

Preparing Video For Download...