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