การจัดการข้อยกเว้นเฉพาะประเภทและข้อความแจ้งเตือน

Transactions and Error Handling in 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';
Transactions and Error Handling in PostgreSQL

ผลลัพธ์จาก exception handler

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)
Transactions and Error Handling in PostgreSQL

ประเภท exception condition ที่พบบ่อย

ชื่อ Condition ตัวอย่าง
unique_violation แทรกค่าซ้ำในคอลัมน์ที่กำหนดเป็น unique
not_null_violation แทรกค่า null ในฟิลด์ที่ไม่อนุญาต null
check_violation ค่าไม่ผ่าน check constraint เช่น ค่า deliciousness สูงกว่า 11
division_by_zero หารด้วย 0

ยังมีประเภทอื่นอีกมาก ดูได้ที่ลิงก์ในอ้างอิงด้านล่าง

1 https://www.postgresql.org/docs/9.4/errcodes-appendix.html
Transactions and Error Handling in PostgreSQL

การดักจับข้อยกเว้นหลายประเภท

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

Transactions and Error Handling in 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';

Transactions and Error Handling in 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)
Transactions and Error Handling in PostgreSQL

มาฝึกกันเถอะ!

Transactions and Error Handling in PostgreSQL

Preparing Video For Download...