Xử lý ngoại lệ cụ thể và thông báo

Giao dịch và Xử lý Lỗi trong PostgreSQL

Jason Myers

Principal Engineer

Bắt một loại ngoại lệ cụ thể

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';
Giao dịch và Xử lý Lỗi trong PostgreSQL

Kết quả của bộ xử lý ngoại lệ

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)
Giao dịch và Xử lý Lỗi trong PostgreSQL

Các loại điều kiện ngoại lệ phổ biến

Tên điều kiện Ví dụ
unique_violation Chèn hai giá trị trùng vào cột unique
not_null_violation Chèn null vào trường không cho phép null
check_violation Vi phạm ràng buộc CHECK, như điểm ngon > 11
division_by_zero Chia cho 0

Còn nhiều mục khác tại liên kết trích dẫn bên dưới

1 https://www.postgresql.org/docs/9.4/errcodes-appendix.html
Giao dịch và Xử lý Lỗi trong PostgreSQL

Bắt nhiều ngoại lệ

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

Giao dịch và Xử lý Lỗi trong PostgreSQL

Bắt riêng nhiều loại ngoại lệ

-- Thêm ngoại lệ 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.';

-- Thêm ngoại lệ not_null_violation
  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';

Giao dịch và Xử lý Lỗi trong PostgreSQL

Kết quả khi bắt nhiều ngoại lệ

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)
Giao dịch và Xử lý Lỗi trong PostgreSQL

Đến lúc áp dụng!

Giao dịch và Xử lý Lỗi trong PostgreSQL

Preparing Video For Download...