获取堆叠诊断信息
堆叠诊断可以获取 PostgreSQL 内部的错误消息和异常细节。让我们回到 patients 表,尝试插入一个超过检测上限的 A1C 值。这样会触发检查约束异常,我们可以将其捕获。您可以在异常处理器中使用堆叠诊断来丰富错误记录。
本练习是课程的一部分
PostgreSQL 中的事务与错误处理
练习说明
- 使用
DECLARE声明两个文本变量exc_message和exc_detail。 - 获取诊断栈,将
MESSAGE_TEXT赋给exc_message,将PG_EXCEPTION_DETAIL赋给exc_detail。 - 将
exc_message和exc_detail分别插入到 errors 表的msg和detail字段中。
交互式实操练习
通过完成这段示例代码来试试这个练习。
DO $$
-- Declare our text variables: exc_message and exc_detail
___
___ text;
exc_detail ___;
BEGIN
INSERT INTO patients (a1c, glucose, fasting)
values (20, 89, TRUE);
EXCEPTION
WHEN others THEN
-- Get the exception message and detail via stacked diagnostics
___ ___ ___
exc_message = ___,
exc_detail = ___;
-- Record the exception message and detail in the errors table
INSERT INTO errors (___, detail) VALUES (exc_message, ___);
END;
$$ language 'plpgsql';
-- Select all the errors recorded
SELECT * FROM errors;