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

การดึงข้อมูล 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;
แก้ไขและรันโค้ด