การดักจับ exception เฉพาะประเภท
มาสร้าง DO function ที่ดักจับกรณีที่ glucose ถูกตั้งค่าเป็น null และบันทึกข้อความระบุชัดเจนว่า Glucose ไม่สามารถเป็น null ได้
แบบฝึกหัดนี้เป็นส่วนหนึ่งของหลักสูตร
Transactions and Error Handling in PostgreSQL
คำแนะนำการฝึกหัด
- ภายใน block
BEGINของ DO function ให้INSERTแถวข้อมูล (a1c=7.5,glucose=nullและfasting=TRUE) ลงในpatients - เพิ่ม exception ประเภท
not_null_violationที่จะ insert"Glucose can not be null."ลงในคอลัมน์ detail ของ errors เมื่อเกิดข้อผิดพลาด
แบบฝึกหัดเชิงโต้ตอบแบบลงมือทำ
ลองทำแบบฝึกหัดนี้โดยเติมโค้ดตัวอย่างนี้ให้สมบูรณ์
-- Make a DO function
DO $$
-- Open a transaction block
BEGIN
INSERT INTO patients (a1c, glucose, fasting)
VALUES (7.5, ___, TRUE);
-- Catch an Exception
EXCEPTION
-- Make it catch not_null_constraint exception types
WHEN ___ ___
-- Insert the proper msg and detail
INSERT INTO errors (___, detail)
VALUES ('failed to insert', '___');
END$$;
-- Select all the errors recorded
SELECT * FROM errors;