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.

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

In 10 seconds

What
GET STACKED DIAGNOSTICS outside a handler
What triggers it
Call GET STACKED DIAGNOSTICS in PL/pgSQL code that is not inside an EXCEPTION handler.
The 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.

The fix

What to do right now

The immediate, application-level response to 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 $$;

Related & next steps

Follow the thread

Everything this error touches — jump straight to the sibling error, term, runbook, or parameter.

Verification

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