開始使用免費開始

取得堆疊診斷

堆疊診斷可以取得 PostgreSQL 內部的錯誤訊息與例外詳細資訊。讓我們回到 patients 資料表,嘗試新增一筆超過檢測上限的 A1C。這會觸發檢查條件(check constraint)的例外,我們可以將其擷取下來。你可以在例外處理常式中使用堆疊診斷,讓錯誤紀錄包含更完整的資訊。

本練習屬於課程

PostgreSQL 的交易與錯誤處理

檢視課程

練習說明

  • 使用 DECLARE 宣告兩個文字型別變數 exc_messageexc_detail
  • 取得診斷堆疊,並將 MESSAGE_TEXT 指派給 exc_message,將 PG_EXCEPTION_DETAIL 指派給 exc_detail
  • exc_messageexc_detail 分別插入 errors 資料表的 msgdetail 欄位。

動手互動練習

試著完成這個範例程式碼,體驗一下這個練習。

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;
編輯並執行程式碼