0Z002ERRORTier 3 — Handle with care✅ HIGH confidencestacked diagnostics accessed without active handler
What this means
SQLSTATE 0Z002 is raised when GET STACKED DIAGNOSTICS is used outside of an exception handler in PL/pgSQL. Stacked diagnostics are only available inside EXCEPTION blocks where there is an active error being handled.
Why it happens
- 1Calling GET STACKED DIAGNOSTICS outside of a PL/pgSQL EXCEPTION block
How to reproduce
GET STACKED DIAGNOSTICS used in normal (non-exception) flow.
DO $
DECLARE msg TEXT;
BEGIN
GET STACKED DIAGNOSTICS msg = MESSAGE_TEXT; -- not inside EXCEPTION block
END $;Fix 1: Move GET STACKED DIAGNOSTICS inside an EXCEPTION block
When inspecting error details from within PL/pgSQL.
DO $
DECLARE msg TEXT;
BEGIN
-- some statement
EXCEPTION WHEN OTHERS THEN
GET STACKED DIAGNOSTICS msg = MESSAGE_TEXT;
RAISE NOTICE 'Error: %', msg;
END $;Why this works
Stacked diagnostics are populated only when an exception is being handled. They must be accessed inside the EXCEPTION block.
Sources
📚 Official docs: https://www.postgresql.org/docs/current/errcodes-appendix.html
📚 Feature docs: https://www.postgresql.org/docs/current/plpgsql-control-structures.html#PLPGSQL-ERROR-TRAPPING
🔧 Source ref: Class 0Z — Diagnostics Exception
Confidence assessment
✅ HIGH confidence
Standard SQLSTATE. Behaviour well-documented in PL/pgSQL error trapping docs.
See also
🔗 Related errors
📄 Reference pages