我想在函数内捕获 Postgres 类型不匹配异常(当提供的函数参数不是参数声明应有的类型时),并使用我自定义的错误响应重新抛出它。如何获得所描述的功能?也许以下异常是由函数调用引发的,并且无法重新引发。我尝试在 Postgres 文档中查找信息,但没有任何结果。
使用多态类型定义一个包装函数并将其扔在那里。它不是严格的捕获和重新抛出,但由于它只会发生在您的错误会被抛出的特定场景中,所以它实际上做了同样的事情。
这是关于函数类型解析行为的 PostgreSQL 文档。这是一个示例 demo at db<>fiddle:
create function f(arg1 int) returns int as $f$ select arg1 $f$ language sql;
select f(42), f('77');--one works as intended, one thanks to type coercion
f | f |
---|---|
42 | 77 |
select f('1'::text);--explicit type cast disables coercion
ERROR: function f(text) does not exist LINE 1: select f('1'::text);--explicit type cast disables coercion ^ HINT: No function matches the given name and argument types. You might need to add explicit type casts.
使用
variadic arg1 anycompatiblearray
重载该函数使其成为与任何其他变体不匹配的调用的包罗万象。
create function f(variadic args anycompatiblearray) returns int as $f$
begin raise exception 'MY CUSTOM MESSAGE: UNRECOGNIZED f() PARAMETER TYPES';
end $f$ language plpgsql;
select f('a'::text);
ERROR: MY CUSTOM MESSAGE: ARGUMENT TYPES PROVIDED FOR f() WERE NOT RECOGNIZED CONTEXT: PL/pgSQL function f(anycompatiblearray) line 2 at RAISE
create table test as select 'a'::text as column1;
select f(column1) from test;
ERROR: MY CUSTOM MESSAGE: ARGUMENT TYPES PROVIDED FOR f() WERE NOT RECOGNIZED CONTEXT: PL/pgSQL function f(anycompatiblearray) line 2 at RAISE
不过,这不适用于未知的文字:
select f('a');
ERROR: function f(unknown) is not unique LINE 2: select f('a'); ^ HINT: Could not choose a best candidate function. You might need to add explicit type casts.
添加更多接受特定类型参数的重载
unknown
,不会削减它:
ERROR: PL/pgSQL functions cannot accept type unknown ERROR: SQL functions cannot have arguments of type unknown