การดึงข้อมูล Stacked Diagnostics
Stacked diagnostics ช่วยดึงข้อความแสดงข้อผิดพลาดภายในของ PostgreSQL และรายละเอียดของ exception ได้ ลองกลับมาที่ตาราง patients แล้วพยายามเพิ่มค่า A1C ที่เกินขีดจำกัดของการทดสอบ ซึ่งจะทำให้เกิด check constraint exception ที่สามารถดักจับได้ จากนั้นนำ stacked diagnostics มาใช้ใน exception handler เพื่อเพิ่มความสมบูรณ์ให้กับการบันทึกข้อผิดพลาด
แบบฝึกหัดนี้เป็นส่วนหนึ่งของหลักสูตร
Transactions and Error Handling in PostgreSQL
คำแนะนำการฝึกหัด
DECLAREตัวแปรสองตัวคือexc_messageและexc_detailเป็นชนิด text- ดึง diagnostics stack และกำหนดให้
exc_messageรับค่าจากMESSAGE_TEXTและexc_detailรับค่าจากPG_EXCEPTION_DETAIL - แทรกค่า
exc_messageและexc_detailลงในฟิลด์msgและdetailของตาราง errors
แบบฝึกหัดเชิงโต้ตอบแบบลงมือทำ
ลองทำแบบฝึกหัดนี้โดยเติมโค้ดตัวอย่างนี้ให้สมบูรณ์
DO $$
-- Declare our text variables: exc_message and exc_detail
___
___ text;
exc_detail ___;
BEGIN
INSERT INTO patients (a1c, glucose, fasting)
values (20, 89, TRUE);
EXCEPTION
WHEN others THEN
-- Get the exception message and detail via stacked diagnostics
___ ___ ___
exc_message = ___,
exc_detail = ___;
-- Record the exception message and detail in the errors table
INSERT INTO errors (___, detail) VALUES (exc_message, ___);
END;
$$ language 'plpgsql';
-- Select all the errors recorded
SELECT * FROM errors;