PL/pgSQL Errors and Messages
Summary: in this tutorial, you will learn how to report messages and raise errors using the raise
statement.
Reporting messages
In PL/pgSQL, you use the raise
statement to issue a message. Here’s the syntax of the raise
statement:
In this syntax:
Level
The level
option determines the error severity with the following values:
debug
log
notice
info
warning
exception
If you don’t specify the level
, the raise
statement will use exception
level that raises an error and stops the current transaction by default. We’ll discuss the raise exception
shortly.
Format
The format
is a string that specifies the message. The format
uses percentage ( %
) placeholders that will be substituted by the arguments.
The number of placeholders must be the same as the number of arguments. Otherwise, PostgreSQL will issue an error:
The following example illustrates the raise
statement that reports different messages at the current time.
Output:
Notice that not all messages are reported back to the client. PostgreSQL only reports the info
, warning
, and notice
level messages back to the client. This is controlled by client_min_messages
and log_min_messages
configuration parameters.
Raising errors
To raise an error, you use the exception
level after the raise
statement. The raise
statement uses the exception
level by default.
Besides raising an error, you can add more information by using the following additional clause:
The option
can be:
hint
: provide the hint message so that the root cause of the error is easier to discover.detail
: give detailed information about the error.errcode
: identify the error code, which can be either by condition name or anSQLSTATE
code. Please refer to the table of error codes and condition names.
The expression
is a string-valued expression.
The following example raises a duplicate email error message:
The following examples illustrate how to raise an SQLSTATE
and its corresponding condition:
Now you can use raise
statement to either raise a message or report an error.
Summary
- Use the
raise
statement to issue a message in PL/pgSQL. - Utilize the
using
clause to provide a hint for the error message.