我有一个名为 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
例子:
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:%',SQLERRM;
RAISE INFO 'Error State:%', SQLSTATE;
RAISE INFO 'Error Context:%', err_context;
return -1;
end;
$body$
language plpgsql;
将显示以下内容:
INFO: Error Context:SQL: "SELECT udf_1()"
但这只是错误的文本表示。你的逻辑不应该依赖它。最好使用自定义错误代码来处理异常逻辑(并在您的函数中引发有意义的异常,以便稍后捕获和处理)。
更新:
另一种解决方案是将您的代码分隔在不同的 block 中,您可以分别捕获这些 block 的异常。在这种情况下,您知道从哪个 block 引发了异常:
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 $$
关于PostgreSQL 9.5 : Exception handling,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40802589/