捕捉特定例外
來建立一個 DO 函式,用來在 glucose 被設定為 null 時加以捕捉,並記錄一則訊息,明確說明 Glucose 不可為 null。
本練習屬於課程
PostgreSQL 的交易與錯誤處理
練習說明
- 在 DO 函式的
BEGIN區塊內,將一列資料INSERT到patients(a1c=7.5、glucose=null、fasting=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;