开始使用免费开始使用

捕获特定异常

让我们编写一个 DO 函数,用于捕获 glucose 被设置为 null 的情况,并记录一条消息,明确说明 Glucose 不能为 null。

本练习是课程的一部分

PostgreSQL 中的事务与错误处理

查看课程

练习说明

  • 在 DO 函数的 BEGIN 块中,向 patientsINSERT 一行(a1c=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;
编辑并运行代码