Sample Header Ad - 728x90

How do I reraise an exception in a PL/pgSQL EXCEPTION block?

14 votes
1 answer
9369 views
Consider the following (incomplete) block of PL/pgSQL inside a function:
CREATE OR REPLACE FUNCTION my_calc(myvar1 NUMERIC, myvar2 NUMERIC)
    RETURNS NUMERIC
    RETURNS NULL ON NULL INPUT
    IMMUTABLE
    LANGUAGE plpgsql
    AS $$
    BEGIN
        RETURN some_third_party_function(myvar1, myvar2);
    EXCEPTION WHEN internal_error THEN
        IF SQLERRM LIKE 'KnownErrorPrefix:%' THEN
            RETURN 0;
        ELSE
            -- Reraise the original exception here
            RAISE EXCEPTION '%', SQLERRM;
        END IF;
    END
    $$
When an unanticipated error occurs, this code will throw a new exception with the same message. However, it won't preserve the original type or context. How can I reraise or rethrow the original exception unmodified?
Asked by jpmc26 (1652 rep)
Jan 30, 2019, 10:57 PM
Last activity: Jan 30, 2019, 11:07 PM