引发并捕获用户定义的异常
Raise and catch user defined exceptions
我在我的代码中经常使用 RAISE EXCEPTION '...' USING ERRCODE='....'
,因为我可以在我的 C# 代码中使用错误代码。但是,我现在想在我的 plpgsql 代码中使用它,如下所示:
BEGIN
...
RAISE EXCEPTION 'Something is wrong' USING ERRCODE='S0001';
EXCEPTION WHEN 'S0001' THEN
-- Handle code S0001
END;
但这不起作用。如何在 plpgsql 中捕获和处理我自己抛出的异常?
您的异常处理子句应如下所示:
EXCEPTION
WHEN SQLSTATE 'S0001'
THEN
...
END;
使用sqlstate
,例如:
drop function if exists test();
create or replace function test()
returns int language plpgsql as $$
begin
raise exception using errcode = 50001;
return 0;
exception when sqlstate '50001' then
return sqlstate;
end $$;
select test();
test
-------
50001
(1 row)
我在我的代码中经常使用 RAISE EXCEPTION '...' USING ERRCODE='....'
,因为我可以在我的 C# 代码中使用错误代码。但是,我现在想在我的 plpgsql 代码中使用它,如下所示:
BEGIN
...
RAISE EXCEPTION 'Something is wrong' USING ERRCODE='S0001';
EXCEPTION WHEN 'S0001' THEN
-- Handle code S0001
END;
但这不起作用。如何在 plpgsql 中捕获和处理我自己抛出的异常?
您的异常处理子句应如下所示:
EXCEPTION
WHEN SQLSTATE 'S0001'
THEN
...
END;
使用sqlstate
,例如:
drop function if exists test();
create or replace function test()
returns int language plpgsql as $$
begin
raise exception using errcode = 50001;
return 0;
exception when sqlstate '50001' then
return sqlstate;
end $$;
select test();
test
-------
50001
(1 row)