用堆叠诊断增强异常处理

PostgreSQL 中的事务与错误处理

Jason Myers

Principal Engineer

捕获更多错误信息

DO $$
BEGIN
   UPDATE inventory SET cost = 35.0 WHERE name = 'Macaron';
   UPDATE inventory SET cost = 3.50 WHERE name = 'Panellets';
EXCEPTION
   WHEN others THEN
       INSERT INTO errors (msg) VALUES ('Max cost is 10!');
       RAISE INFO 'Max cost is 10!';
END; 
$$ language 'plpgsql';
PostgreSQL 中的事务与错误处理

使用堆叠诊断

DO $$
DECLARE
   exc_message text;
   exc_detail text;

BEGIN UPDATE inventory SET cost = 35.0 WHERE name = 'Macaron'; UPDATE inventory SET cost = 3.50 WHERE name = 'Panellets';
EXCEPTION WHEN others THEN GET STACKED DIAGNOSTICS exc_message = MESSAGE_TEXT, exc_detail = PG_EXCEPTION_DETAIL; INSERT INTO errors (msg, detail) VALUES (exc_message, exc_detail); RAISE INFO 'Exception Messaage: % | Exception Details: %', exc_message, exc_detail; END$$;
PostgreSQL 中的事务与错误处理

诊断输出示例

INFO:  Exception Messaage: new row for relation "inventory" violates check constraint 
"cost_check" | Exception Details: Failing row contains (7, 35, Macaron).
DO

postgres=# \x on
Expanded display is on.
postgres=# select msg, detail from errors;
-[ RECORD 1 ]-------------------------------------------------------------------
msg    | new row for relation "inventory" violates check constraint "cost_check"
detail | Failing row contains (7, 35, Macaron).
PostgreSQL 中的事务与错误处理

能拿到哪些信息?

Name Description
RETURNED_SQLSTATE 异常的 SQLSTATE 错误码
COLUMN_NAME 与异常相关的列名
CONSTRAINT_NAME 与异常相关的约束名
MESSAGE_TEXT 异常主消息文本
PG_EXCEPTION_DETAIL 异常详细信息文本(如有)
1 https://www.postgresql.org/docs/12/plpgsql-control-structures.html
PostgreSQL 中的事务与错误处理

更多诊断数据点

Name Description
PG_DATATYPE_NAME 与异常相关的数据类型名
TABLE_NAME 与异常相关的表名
SCHEMA_NAME 与异常相关的模式名
PG_EXCEPTION_HINT 异常提示信息(如有)
PG_EXCEPTION_CONTEXT 异常发生时的调用栈文本
PostgreSQL 中的事务与错误处理

Passons à la pratique !

PostgreSQL 中的事务与错误处理

Preparing Video For Download...