擷取情境堆疊
取得堆疊情境(類似其他語言的 stack trace)是除錯複雜、巢狀函式的有力方式。
在下面的程式碼中,你要在兩層巢狀區塊的例外處理常式裡擷取堆疊情境並加以記錄。接著,在 errors 資料表中檢視輸出,以協助除錯並找出此函式拋出例外的原因。
本練習屬於課程
PostgreSQL 的交易與錯誤處理
練習說明
- 宣告一個文字變數
exc_context,用來存放堆疊情境。 - 在第一個處理常式中,將
PG_EXCEPTION_CONTEXT存入exc_context變數。 - 在第二個處理常式中,將
PG_EXCEPTION_DETAIL存入exc_detail變數。 - 在兩個區塊中都要同時記錄錯誤訊息與堆疊情境。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
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;