PL/pgSQL 错误和消息
在本教程中,您将学习如何使用 raise 语句报告消息和引发错误。此外,您将学习如何使用该 assert 语句将调试检查插入到 PL/pgSQL 块中。
摘要:在本教程中,您将学习如何使用 raise 语句报告消息和引发错误。此外,您将学习如何使用该 assert 语句将调试检查插入到 PL/pgSQL 块中。
报告消息
要引发消息,请使用以下 raise 语句:
raise level format;
让我们 raise 更详细地检查该语句。
等级
继 raise 语句是 level 指定了错误的严重性选项。
PostgreSQL 提供以下级别:
debuglognoticeinfowarningexception
如果不指定 level , 默认情况下, raise 语句将使用 exception 引发错误并停止当前事务的级别。我们将 raise exception 在下一节讨论后者。
格式
的 format 是,用于指定消息的字符串。的 format 用途百分比( % 将由参数取代)占位符。
占位符的数量必须与参数的数量相同,否则PostgreSQL会报错:
[Err] ERROR: too many parameters specified for raise
以下示例说明 raise 了当前报告不同消息的语句。
do $$
begin
raise info 'information message %', now() ;
raise log 'log message %', now();
raise debug 'debug message %', now();
raise warning 'warning message %', now();
raise notice 'notice message %', now();
end $$;
输出:
info: information message 2015-09-10 21:17:39.398+07
warning: warning message 2015-09-10 21:17:39.398+07
notice: notice message 2015-09-10 21:17:39.398+07
请注意,并非所有消息都会报告给客户端。PostgreSQL只报告 info , warning 以及 notice 水平的信息返回给客户端。这由 client_min_messages 和 log_min_messages 配置参数控制。
引发错误
要引发错误,请使用语句 exception 后的级别 raise 。请注意, raise 语句 exception 默认使用级别。
除了引发错误之外,您还可以使用以下附加子句添加更多信息:
using option = expression
该 option 可以是:
message: 设置错误信息hint: 提供提示信息,以便更容易发现错误的根本原因。detail: 提供有关错误的详细信息。errcode:识别错误代码,可以是条件名称,也可以直接是五位字符的SQLSTATE代码。请参阅错误代码和条件名称表。
的 expression 是一个字符串值表达式。以下示例引发重复的电子邮件错误消息:
do $$
declare
email varchar(255) := '[email protected]';
begin
-- check email for duplicate
-- ...
-- report duplicate email
raise exception 'duplicate email: %', email
using hint = 'check the email again';
end $$;
[Err] ERROR: Duplicate email: info@postgresqltutorial.com
HINT: Check the email again
以下示例说明了如何引发 an SQLSTATE 及其相应的条件:
do $$
begin
--...
raise sqlstate '2210b';
end $$;
do $$
begin
--...
raise invalid_regular_expression;
end $$;
现在您可以使用 raise statement 来引发消息或报告错误。