捕获特定异常
让我们编写一个 DO 函数,用于捕获 glucose 被设置为 null 的情况,并记录一条消息,明确说明 Glucose 不能为 null。
本练习是课程的一部分
PostgreSQL 中的事务与错误处理
练习说明
- 在 DO 函数的
BEGIN块中,向patients表INSERT一行(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;