在特定例外時記錄訊息
同時捕捉多個特定例外的一大用途,是能分別處理並記錄獨特的錯誤訊息,幫助你精準了解為什麼發生例外。讓我們在一個兩種錯誤條件都可能出現的情境中來實作。完成練習後,我們會討論為什麼會捕捉到該特定訊息。
本練習屬於課程
PostgreSQL 的交易與錯誤處理
練習說明
- 為
not_null_violation建立例外處理器。 - 當發生
not_null_violation時,在errors資料表中插入"failed to insert"作為msg,以及Glucose can not be null.作為detail。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
-- Make a DO function
DO $$
-- Open a transaction block
___
INSERT INTO patients (a1c, glucose, fasting) values (20, null, TRUE);
-- Catch an Exception
EXCEPTION
-- Make it catch check_violation exception types
WHEN check_violation THEN
-- Insert the proper msg and detail
INSERT INTO errors (msg, detail)
VALUES ('failed to insert', 'A1C is higher than clinically accepted norms.');
-- Make it catch not_null_violation exception types
___ ___ ___
-- Insert the proper msg and detail
INSERT INTO errors (msg, detail)
___ (___, ___);
END$$;
-- Select all the errors recorded
SELECT * FROM errors;