SQLSTATE 0Z002Severity lowLab verified

Incident brief

GET STACKED DIAGNOSTICS outside a handler

GET STACKED DIAGNOSTICS reads details of the exception currently being handled, so it is only valid inside an EXCEPTION handler; using it elsewhere raises this diagnostics exception.

What lands in your log

ERROR: GET STACKED DIAGNOSTICS cannot be used outside an exception handler

Reproduced on PostgreSQL 18.4Verified 2026-07-24 (isolated lab, PostgreSQL 18.4)Verified against PostgreSQL 18.4 in an isolated lab environment

In 10 seconds

What triggers it
Call GET STACKED DIAGNOSTICS in PL/pgSQL code that is not inside an EXCEPTION handler.
Fix
Move the GET STACKED DIAGNOSTICS into an EXCEPTION ... handler block.
Proof
Reproduced on PostgreSQL 18.4 → A DO block reproduces SQLSTATE 0Z002; GET STACKED DIAGNOSTICS outside a handler is rejected, naming the statement in the CONTEXT.

Fix

What to do right now

Application-level steps for this error.

  • Move the GET STACKED DIAGNOSTICS into an EXCEPTION ... handler block.
  • Use GET CURRENT DIAGNOSTICS (not STACKED) if you need diagnostics outside a handler.
Fix SQL
-- Read stacked diagnostics only inside an EXCEPTION handler.
DO $$ DECLARE msg text; BEGIN BEGIN RAISE EXCEPTION 'boom'; EXCEPTION WHEN others THEN GET STACKED DIAGNOSTICS msg = MESSAGE_TEXT; RAISE NOTICE 'caught: %', msg; END; END $$;

Connected

Everything this error touches

Every page this SQLSTATE connects to: the concept that explains it, the runbooks that fix it, the parameters you tune to prevent it, and the sibling errors it travels with. All real cross-references. Jump straight in, or open the full interactive map.

Open in the interactive map →

Verification

PG 18.4
Last verified
2026-07-24 (isolated lab, PostgreSQL 18.4)
Verification scope
Verified against PostgreSQL 18.4 in an isolated lab environment
Audit status
reviewed
ShareLinkedInX

Went further?

Pro unlocks the second lab proof

Free page stops the bleeding. Pro adds the operational test, SQLSTATE audit, and deeper evidence, same error, more certainty.

FollowSubstackLinkedInnew errors · lab notes · hiring loops