开始使用免费开始使用

为特定异常记录日志消息

针对多个特定异常进行捕获的最佳用法之一,是分别处理并记录独立的错误消息,帮助您准确了解异常发生的原因。让我们在一个两种错误条件都可能出现的场景中应用这一点。练习结束后,我们会讨论为什么它会捕获到该特定消息。

本练习是课程的一部分

PostgreSQL 中的事务与错误处理

查看课程

练习说明

  • not_null_violation 构建一个异常处理器。
  • 如果发生 not_null_violation,向 errors 表插入一条记录,其中 msg"failed to insert"detailGlucose can not be null.

交互式实操练习

通过完成这段示例代码来试试这个练习。

-- 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;
编辑并运行代码