PG
PRO
0Z002ERRORTier 3 — Handle with care✅ HIGH confidence

stacked diagnostics accessed without active handler

Category: Diagnostics ExceptionVersions: All Postgres versions

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

  1. 1Calling GET STACKED DIAGNOSTICS outside of a PL/pgSQL EXCEPTION block

How to reproduce

GET STACKED DIAGNOSTICS used in normal (non-exception) flow.

trigger — this will ERROR
DO $
DECLARE msg TEXT;
BEGIN
  GET STACKED DIAGNOSTICS msg = MESSAGE_TEXT; -- not inside EXCEPTION block
END $;
ERROR: stacked diagnostics accessed without active handler

Fix 1: Move GET STACKED DIAGNOSTICS inside an EXCEPTION block

When inspecting error details from within PL/pgSQL.

fix
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

Confidence assessment

✅ HIGH confidence

Standard SQLSTATE. Behaviour well-documented in PL/pgSQL error trapping docs.

See also

🔗 Related errors

📄 Reference pages

GET STACKED DIAGNOSTICSPL/pgSQL Exception Handling
⚙️ This error reference was generated with AI assistance and reviewed for accuracy. Examples are provided to illustrate common scenarios and may not cover every case. Always test fixes in a development environment before applying to production. Spotted an error? Suggest a correction →