Обробка конкретних винятків і повідомлення

Транзакції та обробка помилок у PostgreSQL

Jason Myers

Principal Engineer

Перехоплення конкретного типу винятку

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';
Транзакції та обробка помилок у PostgreSQL

Вивід нашого обробника винятків

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)
Транзакції та обробка помилок у PostgreSQL

Поширені типи умов винятків

Condition Name Example
unique_violation Insert two of the same value in a unique column
not_null_violation Insert null into a field that doesn't allow nulls
check_violation Failing a check constraint such as being higher than 11 in deliciousness
division_by_zero Dividing by 0

So many more at the link in the citation below

1 https://www.postgresql.org/docs/9.4/errcodes-appendix.html
Транзакції та обробка помилок у PostgreSQL

Перехоплення кількох винятків

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

Транзакції та обробка помилок у PostgreSQL

Окреме перехоплення кількох типів винятків

-- 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';

Транзакції та обробка помилок у PostgreSQL

Вивід для перехоплення кількох винятків

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)
Транзакції та обробка помилок у PostgreSQL

Час застосувати!

Транзакції та обробка помилок у PostgreSQL

Preparing Video For Download...