Get Stacked Diagnostics Capture Sqlstate

Inside an EXCEPTION handler, GET STACKED DIAGNOSTICS exposes the caught failure's SQLSTATE, message text, and PL/pgSQL call context.

SqlResilience

Code

snippet
-- EXCEPTION 处理块里 capture SQLSTATE:GET STACKED DIAGNOSTICS 读出错误细节
CREATE OR REPLACE FUNCTION divide(numerator numeric, denominator numeric)
RETURNS text
LANGUAGE plpgsql AS $$
DECLARE
    v_state   text;
    v_message text;
    v_context text;
BEGIN
    RETURN numerator / denominator;
EXCEPTION
    WHEN division_by_zero THEN
        GET STACKED DIAGNOSTICS
            v_state   = RETURNED_SQLSTATE,
            v_message = MESSAGE_TEXT,
            v_context = PG_EXCEPTION_CONTEXT;
        RETURN format('[%s] %s | %s', v_state, v_message, v_context);
END;
$$;

SELECT divide(10, 2) AS plain_result;
SELECT divide(10, 0) AS handled_result;

DROP FUNCTION divide;

What the handler captures

divide(numerator numeric, denominator numeric) returns text, and the only statement in its body is RETURN numerator / denominator. The EXCEPTION WHEN division_by_zero branch is the single error path: GET STACKED DIAGNOSTICS copies RETURNED_SQLSTATE into v_state, MESSAGE_TEXT into v_message, and PG_EXCEPTION_CONTEXT into v_context. The handler returns them joined by format('[%s] %s | %s', ...), so the caller receives one text value carrying the state code, the message, and the call context.

Two call shapes

SELECT divide(10, 2) AS plain_result divides cleanly, so plain_result holds the numeric quotient cast to text. SELECT divide(10, 0) AS handled_result raises division_by_zero inside the function; the handler catches it, and handled_result holds the formatted diagnostics string instead of the error escaping to the client. DROP FUNCTION divide; removes the function after the two calls.

Interactive Tools for This Topic