PostgreSQL 9.5:异常处理

前端之家收集整理的这篇文章主要介绍了PostgreSQL 9.5:异常处理前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一个名为employee的表,有两列,并为其创建了两个函数
插入和更新操作.这两个函数将通过另一个函数调用
名为udf_3()的函数.

我想对第三个函数udf_3()进行异常处理
给我详细说明哪个函数错误.

– 表:员工

create table employee
(
 id int,name varchar(10)
);

功能1:用于插入的udf_1().

create or replace function udf_1()
returns void as
$body$
begin

        insert into employee values(1,'Mak');
end;
$body$
language plpgsql;

功能2:udf_2()用于更新.

create or replace function udf_2()
returns void as
$body$
begin

        update employee
        set a_id = 99
        where name = 'Mak';

end;
$body$
language plpgsql;

功能3:udf_3()用于调用上述所有功能.

create or replace function udf_3()
returns int as
$body$
begin
    perform udf_1();

    perform udf_2();

    return 0;

    exception 
    when others then
        RAISE INFO 'Error Name:%',sqlERRM;
        RAISE INFO 'Error State:%',sqlSTATE;
        return -1;

end;
$body$
language plpgsql;

功能调用

select * from udf_3();

例外:

INFO:  Error Name:column "a_id" of relation "employee" does not exist
INFO:  Error State:42703

问题:我能够获得异常但是无法从哪个函数获取异常.

解决方法

根据文件

Within an exception handler,one may also retrieve information about the current exception by using the GET STACKED DIAGNOSTICS command

https://www.postgresql.org/docs/9.5/static/plpgsql-control-structures.html#PLPGSQL-EXCEPTION-DIAGNOSTICS

例:

create or replace function udf_3()
returns int as
$body$
declare
    err_context text;
begin
    perform udf_1();

    perform udf_2();

    return 0;

    exception 
    when others then
        GET STACKED DIAGNOSTICS err_context = PG_EXCEPTION_CONTEXT;
        RAISE INFO 'Error Name:%',sqlSTATE;
        RAISE INFO 'Error Context:%',err_context;
        return -1;

end;
$body$
language plpgsql;

显示以下内容

INFO: Error Context:sql: "SELECT udf_1()"

但这只是错误的文本表示.你的逻辑不应该依赖它.最好使用自定义错误代码来处理异常逻辑(并在函数中引发有意义的异常,以便稍后捕获和处理).

更新:

另一种解决方案是将您的代码分成不同的块,您可以单独捕获异常.在这种情况下,您知道从哪个块引发了异常:

DO $$
BEGIN

    -- Block 1
    BEGIN
        -- any code that might raise an exception
        RAISE EXCEPTION 'Exception 1'; -- for example
    EXCEPTION 
    WHEN others THEN    
        RAISE INFO 'Caught in Block 1';
    END;

    -- Block 2
    BEGIN
        -- any code that might raise an exception
        RAISE EXCEPTION 'Exception 2'; -- for example
    EXCEPTION 
    WHEN others THEN    
        RAISE INFO 'Caught in Block 2';
    END;

END $$

猜你在找的Postgre SQL相关文章