0Z002
PostgreSQLERRORCriticalDiagnostics ExceptionHIGH confidence

stacked 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
  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
trigger — this will error
DO $
DECLARE msg TEXT;
BEGIN
  GET STACKED DIAGNOSTICS msg = MESSAGE_TEXT; -- not inside EXCEPTION block
END $;

expected output

ERROR:  stacked diagnostics accessed without active handler

Fix

Move GET STACKED DIAGNOSTICS inside an EXCEPTION block

WHEN When inspecting error details from within PL/pgSQL.

Move GET STACKED DIAGNOSTICS inside an EXCEPTION block
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 documentation ↗

Class 0Z — Diagnostics Exception

Content generated with AI assistance and reviewed for accuracy. Found an error? hello@errcodes.dev

← All PostgreSQL errors