开始使用免费开始使用

获取堆叠诊断信息

堆叠诊断可以获取 PostgreSQL 内部的错误消息和异常细节。让我们回到 patients 表,尝试插入一个超过检测上限的 A1C 值。这样会触发检查约束异常,我们可以将其捕获。您可以在异常处理器中使用堆叠诊断来丰富错误记录。

本练习是课程的一部分

PostgreSQL 中的事务与错误处理

查看课程

练习说明

  • 使用 DECLARE 声明两个文本变量 exc_messageexc_detail
  • 获取诊断栈,将 MESSAGE_TEXT 赋给 exc_message,将 PG_EXCEPTION_DETAIL 赋给 exc_detail
  • exc_messageexc_detail 分别插入到 errors 表的 msgdetail 字段中。

交互式实操练习

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

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