捕获上下文堆栈
获取堆栈上下文(类似于其他语言中的堆栈跟踪)是调试复杂且嵌套函数的强大方式。
在下面的代码中,您需要在两个嵌套块的异常处理器中捕获堆栈上下文并进行记录。然后,在 errors 表中查看输出,帮助定位该函数引发异常的原因。
本练习是课程的一部分
PostgreSQL 中的事务与错误处理
练习说明
- 声明一个文本变量
exc_context,用于保存堆栈上下文。 - 在第一个处理器中,将
PG_EXCEPTION_CONTEXT存入变量exc_context。 - 在第二个处理器中,将
PG_EXCEPTION_DETAIL存入变量exc_detail。 - 在两个块中都记录错误消息和堆栈上下文。
交互式实操练习
通过完成这段示例代码来试试这个练习。
DO $$
DECLARE
exc_message text;
exc_details text;
-- Declare a variable, exc_context to hold the exception context
___ ___;
BEGIN
BEGIN
INSERT INTO patients (a1c, glucose, fasting) values (5.6, 93, TRUE),
(6.3, 111, TRUE),(4.7, 65, TRUE);
EXCEPTION
WHEN others THEN
-- Store the exception context in exc_context
GET STACKED DIAGNOSTICS exc_message = MESSAGE_TEXT,
___ = ___;
-- Record both the msg and the context
INSERT INTO errors (msg, context)
VALUES (___, ___);
END;
BEGIN
UPDATE patients set fasting = 'true' where id=1;
EXCEPTION
WHEN others THEN
-- Store the exception detail in exc_details
GET STACKED DIAGNOSTICS exc_message = MESSAGE_TEXT,
___ = ___;
INSERT INTO errors (___, ___)
VALUES (exc_message, exc_context);
END;
END$$;
SELECT * FROM errors;