八月 21, 2023
摘要:在本教程中,您将学习如何使用raise语句报告消息和引发错误。此外,您还将学习如何使用assert语句将调试检查插入到 PL/pgSQL 块中。
目录
报告消息
要发出消息,您可以使用如下raise语句:
raise level format;
让我们更详细地研究一下raise语句。
消息级别
raise语句后面是指定错误严重性的level选项。
PostgreSQL 提供以下级别:
debuglognoticeinfowarningexception
如果您不指定level,默认情况下,raise语句会使用exception级别引发错误并停止当前事务。我们将在下一节中讨论raise exception。
格式
format是指定消息的字符串。format使用将被参数替换的百分号 (%) 占位符。
占位符的数量必须与参数的数量相同,否则 PostgreSQL 将发出错误:
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配置参数控制的。
引发错误
要引发错误,请在raise语句后使用exception级别。请注意,raise语句默认使用exception级别。
除了引发错误之外,您还可以使用以下附加子句添加更多信息:
using option = expression
option可以是:
message: 设置错误信息。hint: 提供提示信息,以便更容易发现错误的根本原因。detail: 给出有关错误的详细信息。errcode: 标识错误代码,可以是异常名称,也可以是直接的五字符SQLSTATE代码。请参阅错误代码和异常名称表。
expression是一个字符串值表达式。以下示例引发了一条重复电子邮件的错误消息:
do $$
declare
email varchar(255) := 'info@rockdata.net';
begin
-- check email for duplicate
-- ...
-- report duplicate email
raise exception 'duplicate email: %', email
using hint = 'check the email again';
end $$;
ERROR: Duplicate email: info@rockdata.net
HINT: Check the email again
以下示例说明了如何使用使用SQLSTATE代码及其对应的异常名称,引发一个错误:
do $$
begin
--...
raise sqlstate '2210b';
end $$;
do $$
begin
--...
raise invalid_regular_expression;
end $$;
现在您可以使用raise语句来报告消息或引发错误。