Transactions and Error Handling in PostgreSQL
Jason Myers
Principal Engineer
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';
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$$;
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).
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 |
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