特定异常处理与消息

PostgreSQL 中的事务与错误处理

Jason Myers

Principal Engineer

捕获特定类型的异常

DO $$
BEGIN
    UPDATE inventory SET quantity = quantity - 1 WHERE name in ('flour', 'sugar');
EXCEPTION
    WHEN check_violation THEN
           INSERT INTO errors (msg) VALUES ('Quantity can not be less than 0.');
           RAISE INFO 'Quantity can not be less than 0.';
END; 
$$ language 'plpgsql';
PostgreSQL 中的事务与错误处理

异常处理器的输出

INFO:  Quantity can not be less than 0.
DO
postgres=# select * from errors;
 error_id | state |               msg                | detail | context
^---------+-------+----------------------------------+--------+---------
        1 |       | Quantity can not be less than 0. |        |
(1 row)
PostgreSQL 中的事务与错误处理

常见异常条件类型

Condition Name Example
unique_violation 在唯一列中插入重复值
not_null_violation 向不允许为空的字段插入 null
check_violation 未通过检查约束,如美味度大于 11
division_by_zero 被 0 除

更多类型见下方引用链接

1 https://www.postgresql.org/docs/9.4/errcodes-appendix.html
PostgreSQL 中的事务与错误处理

捕获多个异常

DO $$
BEGIN
    UPDATE inventory SET quantity = quantity - 6, cost = null 
    WHERE name='oatmeal dark chocolate';

PostgreSQL 中的事务与错误处理

分别捕获多种异常类型

-- Add check_violation exception
EXCEPTION
  WHEN check_violation THEN
     INSERT INTO errors (msg) VALUES ('Quantity can not be less than 0.');
     RAISE INFO 'Quantity can not be less than 0.';

-- Add non-null exception
  WHEN not_null_violation THEN
     INSERT INTO errors (msg) VALUES ('Cost can not be null.');
     RAISE INFO 'Cost can not be null.';
END; $$ language 'plpgsql';

PostgreSQL 中的事务与错误处理

多异常捕获的输出

INFO:  Cost can not be null.
DO
postgres=# select * from errors;
 error_id | state |               msg                | detail | context
^---------+-------+----------------------------------+--------+---------
        2 |       | Cost can not be null.            |        |
(1 row)
PostgreSQL 中的事务与错误处理

该你动手了!

PostgreSQL 中的事务与错误处理

Preparing Video For Download...