開始使用免費開始

捕捉特定例外

來建立一個 DO 函式,用來在 glucose 被設定為 null 時加以捕捉,並記錄一則訊息,明確說明 Glucose 不可為 null。

本練習屬於課程

PostgreSQL 的交易與錯誤處理

檢視課程

練習說明

  • 在 DO 函式的 BEGIN 區塊內,將一列資料 INSERTpatientsa1c=7.5glucose=nullfasting=TRUE)。
  • 加上一個 not_null_violation 例外,當發生錯誤時,將 "Glucose can not be null." 插入到 errors 的 detail 欄位。

動手互動練習

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

-- Make a DO function
DO $$
-- Open a transaction block
BEGIN
    INSERT INTO patients (a1c, glucose, fasting) 
    VALUES (7.5, ___, TRUE);
-- Catch an Exception                                                               
EXCEPTION
	-- Make it catch not_null_constraint exception types
    WHEN ___ ___
    	-- Insert the proper msg and detail
       INSERT INTO errors (___, detail) 
       VALUES ('failed to insert', '___');
END$$;
                                                                     
-- Select all the errors recorded
SELECT * FROM errors;
編輯並執行程式碼