การบันทึก context stack
การดึง stack context ซึ่งทำหน้าที่คล้าย stack trace ในภาษาอื่น ๆ เป็นวิธีที่มีประสิทธิภาพในการดีบักฟังก์ชันที่ซับซ้อนและมีการซ้อนกัน
ในโค้ดด้านล่าง เราต้องการบันทึก stack context และจัดเก็บไว้ในตัวจัดการข้อยกเว้นของทั้งสองบล็อกที่ซ้อนกัน จากนั้นนำข้อมูลในตาราง errors มาตรวจสอบเพื่อช่วยดีบักสาเหตุของข้อยกเว้นในฟังก์ชันนี้
แบบฝึกหัดนี้เป็นส่วนหนึ่งของหลักสูตร
Transactions and Error Handling in PostgreSQL
คำแนะนำการฝึกหัด
- ประกาศตัวแปร text ชื่อ
exc_contextเพื่อเก็บ stack context - จัดเก็บค่าจาก
PG_EXCEPTION_CONTEXTลงในตัวแปรexc_contextในตัวจัดการตัวแรก - จัดเก็บค่าจาก
PG_EXCEPTION_DETAILลงในตัวแปรexc_detailในตัวจัดการตัวที่สอง - บันทึกทั้งข้อความแสดงข้อผิดพลาดและ stack context ในทั้งสองบล็อก
แบบฝึกหัดเชิงโต้ตอบแบบลงมือทำ
ลองทำแบบฝึกหัดนี้โดยเติมโค้ดตัวอย่างนี้ให้สมบูรณ์
DO $$
DECLARE
exc_message text;
exc_details text;
-- Declare a variable, exc_context to hold the exception context
___ ___;
BEGIN
BEGIN
INSERT INTO patients (a1c, glucose, fasting) values (5.6, 93, TRUE),
(6.3, 111, TRUE),(4.7, 65, TRUE);
EXCEPTION
WHEN others THEN
-- Store the exception context in exc_context
GET STACKED DIAGNOSTICS exc_message = MESSAGE_TEXT,
___ = ___;
-- Record both the msg and the context
INSERT INTO errors (msg, context)
VALUES (___, ___);
END;
BEGIN
UPDATE patients set fasting = 'true' where id=1;
EXCEPTION
WHEN others THEN
-- Store the exception detail in exc_details
GET STACKED DIAGNOSTICS exc_message = MESSAGE_TEXT,
___ = ___;
INSERT INTO errors (___, ___)
VALUES (exc_message, exc_context);
END;
END$$;
SELECT * FROM errors;