เริ่มต้นใช้งานเริ่มต้นใช้งานได้ฟรี

การดักจับ 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;
แก้ไขและรันโค้ด