取得堆疊診斷
堆疊診斷可以取得 PostgreSQL 內部的錯誤訊息與例外詳細資訊。讓我們回到 patients 資料表,嘗試新增一筆超過檢測上限的 A1C。這會觸發檢查條件(check constraint)的例外,我們可以將其擷取下來。你可以在例外處理常式中使用堆疊診斷,讓錯誤紀錄包含更完整的資訊。
本練習屬於課程
PostgreSQL 的交易與錯誤處理
練習說明
- 使用
DECLARE宣告兩個文字型別變數exc_message與exc_detail。 - 取得診斷堆疊,並將
MESSAGE_TEXT指派給exc_message,將PG_EXCEPTION_DETAIL指派給exc_detail。 - 將
exc_message與exc_detail分別插入 errors 資料表的msg與detail欄位。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
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;