Enhancing exception handling with stacked diagnostics

Transactions and Error Handling in PostgreSQL

Jason Myers

Principal Engineer

Capturing more error information

DO $$
BEGIN
   UPDATE inventory SET cost = 35.0 WHERE name = 'Macaron';
   UPDATE inventory SET cost = 3.50 WHERE name = 'Panellets';
EXCEPTION
   WHEN others THEN
       INSERT INTO errors (msg) VALUES ('Max cost is 10!');
       RAISE INFO 'Max cost is 10!';
END; 
$$ language 'plpgsql';
Transactions and Error Handling in PostgreSQL

Using stacked diagnostics

DO $$
DECLARE
   exc_message text;
   exc_detail text;

BEGIN UPDATE inventory SET cost = 35.0 WHERE name = 'Macaron'; UPDATE inventory SET cost = 3.50 WHERE name = 'Panellets';
EXCEPTION WHEN others THEN GET STACKED DIAGNOSTICS exc_message = MESSAGE_TEXT, exc_detail = PG_EXCEPTION_DETAIL; INSERT INTO errors (msg, detail) VALUES (exc_message, exc_detail); RAISE INFO 'Exception Messaage: % | Exception Details: %', exc_message, exc_detail; END$$;
Transactions and Error Handling in PostgreSQL

Example diagnostic output

INFO:  Exception Messaage: new row for relation "inventory" violates check constraint 
"cost_check" | Exception Details: Failing row contains (7, 35, Macaron).
DO

postgres=# \x on
Expanded display is on.
postgres=# select msg, detail from errors;
-[ RECORD 1 ]-------------------------------------------------------------------
msg    | new row for relation "inventory" violates check constraint "cost_check"
detail | Failing row contains (7, 35, Macaron).
Transactions and Error Handling in PostgreSQL

So what all can you get?

Name Description
RETURNED_SQLSTATE the SQLSTATE error code of the exception
COLUMN_NAME the name of the column related to exception
CONSTRAINT_NAME the name of the constraint related to exception
MESSAGE_TEXT the text of the exception's primary message
PG_EXCEPTION_DETAIL the text of the exception's detail message, if any
1 https://www.postgresql.org/docs/12/plpgsql-control-structures.html
Transactions and Error Handling in PostgreSQL

More diagnostic datapoints

Name Description
PG_DATATYPE_NAME the name of the data type related to exception
TABLE_NAME the name of the table related to exception
SCHEMA_NAME the name of the schema related to exception
PG_EXCEPTION_HINT the text of the exception's hint message, if any
PG_EXCEPTION_CONTEXT line(s) of text of the call stack at the time of the exception
Transactions and Error Handling in PostgreSQL

Let's practice!

Transactions and Error Handling in PostgreSQL

Preparing Video For Download...