Sub topic 9
Raising and handling errors
This chapter assumes you can write a basic PL/pgSQL function, use SELECT INTO and FOUND, and read a CREATE FUNCTION statement. It covers how a function reports problems with RAISE, how an EXCEPTION block catches them, and what each choice costs.
How errors behave by default
When a statement inside a function fails, PostgreSQL abandons the function and aborts the whole surrounding transaction. The caller sees an error with a message and a five-character SQLSTATE code. Nothing the function did survives, unless a block inside it caught the error.
Two tools control this behavior:
RAISEcreates messages and errors.- A block with an
EXCEPTIONsection catches errors and decides what happens next.
RAISE: messages and errors
RAISE takes a level, a format string, and optional arguments. Each % in the format string is replaced by the next argument. Write %% for a literal percent sign.
| Level | Effect |
|---|---|
| `DEBUG`, `LOG`, `INFO` | Sends a message. Whether it appears in the client or the server log depends on settings. |
| `NOTICE` | Sends a message to the client. This is the default level if you write none. |
| `WARNING` | Sends a more severe message to the client. |
| `EXCEPTION` | Aborts the current block and raises an error. This is also the default if you give no level. |
DO $$
BEGIN
RAISE NOTICE 'processing order %', 42;
RAISE WARNING 'stock for item % is below %%', 7, 10;
RAISE EXCEPTION 'cannot continue';
END;
$$;The first two messages appear as notices, and the last statement raises an error.
Adding detail with USING
An error should carry enough information for a caller to react in code, not only for a person to read. The USING clause attaches options:
ERRCODEsets the SQLSTATE. You can give a condition name such ascheck_violationor a literal five-character code.DETAILandHINTadd extra text.TABLE,COLUMN,CONSTRAINT, andSCHEMAidentify the object involved.
The following function uses a standard code for bad input and a custom code for a business rule:
CREATE TABLE accounts (
id integer PRIMARY KEY,
balance numeric NOT NULL CHECK (balance >= 0)
);
INSERT INTO accounts VALUES (1, 100);
CREATE FUNCTION withdraw(p_account integer, p_amount numeric)
RETURNS numeric
LANGUAGE plpgsql
AS $$
DECLARE
v_balance numeric;
BEGIN
IF p_amount IS NULL OR p_amount <= 0 THEN
RAISE EXCEPTION 'amount must be positive, got %', p_amount
USING ERRCODE = 'invalid_parameter_value',
HINT = 'Pass an amount greater than zero.';
END IF;
UPDATE accounts
SET balance = balance - p_amount
WHERE id = p_account AND balance >= p_amount
RETURNING balance INTO v_balance;
IF NOT FOUND THEN
RAISE EXCEPTION 'cannot withdraw % from account %', p_amount, p_account
USING ERRCODE = 'BK001',
DETAIL = 'The account does not exist or has insufficient funds.';
END IF;
RETURN v_balance;
END;
$$;
SELECT withdraw(1, 30);
SELECT withdraw(1, 500);The second call fails with SQLSTATE BK001. A client can test for that code instead of parsing the message text.
EXCEPTION blocks
Any BEGIN ... END block can end with an EXCEPTION section. If a statement in the block body raises an error, PostgreSQL abandons the body. It rolls back every database change the body made, then runs the first WHEN branch that matches. If no branch matches, the error continues to the enclosing block.
CREATE FUNCTION safe_divide(a numeric, b numeric)
RETURNS numeric
LANGUAGE plpgsql
IMMUTABLE
AS $$
BEGIN
RETURN a / b;
EXCEPTION
WHEN division_by_zero THEN
RETURN NULL;
END;
$$;
SELECT safe_divide(10, 4), safe_divide(10, 0);A WHEN branch can match:
- a condition name, such as
unique_violation,foreign_key_violation,no_data_found, ortoo_many_rows - a literal SQLSTATE, written as
WHEN SQLSTATE '23505' - a whole class, by listing its condition name, such as
WHEN integrity_constraint_violation OTHERS, which matches nearly everything
You can combine alternatives with OR. OTHERS does not catch QUERY_CANCELED or ASSERT_FAILURE, so a user cancelling a query is not swallowed by accident.
What the handler can see
Inside a handler, two special variables are available. SQLSTATE holds the code, and SQLERRM holds the message. For more fields, use GET STACKED DIAGNOSTICS:
CREATE TABLE job_errors (
id bigserial PRIMARY KEY,
job text,
sqlstate text,
message text,
detail text,
logged_at timestamptz NOT NULL DEFAULT now()
);
CREATE FUNCTION run_job(p_job text, p_divisor integer)
RETURNS boolean
LANGUAGE plpgsql
AS $$
DECLARE
v_state text;
v_msg text;
v_detail text;
BEGIN
PERFORM 10 / p_divisor;
RETURN true;
EXCEPTION
WHEN OTHERS THEN
GET STACKED DIAGNOSTICS
v_state = RETURNED_SQLSTATE,
v_msg = MESSAGE_TEXT,
v_detail = PG_EXCEPTION_DETAIL;
INSERT INTO job_errors (job, sqlstate, message, detail)
VALUES (p_job, v_state, v_msg, v_detail);
RETURN false;
END;
$$;
SELECT run_job('nightly', 0);
SELECT sqlstate, message FROM job_errors;The INSERT into job_errors survives, because it runs in the handler after the failed body was rolled back. Other useful items are PG_EXCEPTION_HINT, PG_EXCEPTION_CONTEXT (the call stack), CONSTRAINT_NAME, TABLE_NAME, and COLUMN_NAME.
Re-raising
A handler that only does part of the work should pass the error on. A bare RAISE; with no arguments, written inside a handler, re-raises the original error with its code, message, and detail intact. You can also raise a new error that explains the context:
EXCEPTION
WHEN foreign_key_violation THEN
RAISE EXCEPTION 'order % references a missing customer', p_order_id
USING ERRCODE = 'foreign_key_violation';Retrying after a conflict
A common use of a handler is to recover from a race. This function increments a counter, inserts the row if it is missing, and retries if another session inserted it first:
CREATE TABLE tags (
name text PRIMARY KEY,
uses integer NOT NULL DEFAULT 1
);
CREATE FUNCTION bump_tag(p_name text)
RETURNS void
LANGUAGE plpgsql
AS $$
BEGIN
LOOP
UPDATE tags SET uses = uses + 1 WHERE name = p_name;
IF FOUND THEN
RETURN;
END IF;
BEGIN
INSERT INTO tags (name) VALUES (p_name);
RETURN;
EXCEPTION
WHEN unique_violation THEN
NULL; -- someone else inserted first; loop and update instead
END;
END LOOP;
END;
$$;In modern PostgreSQL, INSERT ... ON CONFLICT DO UPDATE does the same job in one statement. Prefer it when it fits, and use the loop pattern when the recovery logic is more complex.
The cost of an EXCEPTION block
A block with an EXCEPTION section opens a subtransaction (an internal savepoint) every time it is entered. This is what allows the rollback, but it has costs:
- Each entry consumes a subtransaction ID. Many such blocks per transaction, especially inside loops, add overhead. Heavy use can also slow concurrent queries.
- The body's changes are undone completely, including inserts and updates made before the failing statement.
- Variable assignments are not rolled back. Local variables keep the values they had when the error occurred.
Choosing between the approaches
Use these guidelines:
- If you can test a condition cheaply, test it with
IForFOUNDand skip the exception. For example,IF NOT FOUND THEN RAISE ...is cheaper than relying onSTRICTand catchingNO_DATA_FOUND. - Use an
EXCEPTIONblock when the failure is something you cannot check beforehand, such as a race on a unique key or a cast that might fail. - Let errors you cannot fix propagate. The caller, or the transaction as a whole, is usually the right place to decide.
ASSERT for internal checks
ASSERT condition, 'message' raises an ASSERT_FAILURE error when the condition is false or null. It is meant for checking your own assumptions during development. Setting plpgsql.check_asserts to off disables it, so never use it to validate user input.
DO $$
DECLARE
v_rows integer := 0;
BEGIN
ASSERT v_rows > 0, 'expected at least one row';
END;
$$;Common mistakes
- Matching on message text. Messages change with language settings and versions. Match on SQLSTATE or condition name.
- Expecting a partial commit. Changes made before the failing statement in the same protected block are lost. Only work done outside that block, or in the handler, remains.
- Forgetting that the handler can fail too. An error raised inside a handler is not caught by the same block's
EXCEPTIONsection. It goes to the enclosing block. - Using
RAISE NOTICEas the only error report. Notices do not stop execution, and many clients ignore them.
Exercise
A function contains BEGIN INSERT INTO log(msg) VALUES ('start'); PERFORM 1/0; EXCEPTION WHEN division_by_zero THEN RETURN -1; END;. After it returns -1, does the log table contain the 'start' row, and why?
Show answer
No. The INSERT ran in the block body, and the error rolled back everything the body did when the handler took over. Only statements executed in the handler, or outside the block, would persist.
Exercise
Write the WHEN clause that catches both unique and foreign key violations by SQLSTATE class, and then re-raises the original error unchanged after logging. Which statement re-raises it?
Show answer
WHEN integrity_constraint_violation THEN (the class 23 condition name) followed by the logging statement and a bare RAISE;. A bare RAISE; inside a handler re-raises the original error with its code, message, and detail.