PostgreSQL custom exceptions?

In Firebird, we can declare custom exceptions, for example:

CREATE EXCEPTION EXP_CUSTOM_0 'Exception: Custom Exception';

they are stored at the database level. In stored procedures, we can make an exception like this:

EXCEPTION EXP_CUSTOM_0;

Is there an equivalent in PostgreSQL?

+2


a source to share


1 answer


No not like this. But you can raise and maintain your own exceptions, no problem:

CREATE TABLE exceptions(
    id serial primary key,
    MESSAGE text, 
    DETAIL text, 
    HINT text, 
    ERRCODE text
);

INSERT INTO exceptions (message, detail, hint, errcode) VALUES ('wrong', 'really wrong!', 'fix this problem', 'P0000');

CREATE OR REPLACE FUNCTION foo() RETURNS int LANGUAGE plpgsql AS
$$
DECLARE
    row record;
BEGIN
    PERFORM * FROM fox; -- does not exist, undefined_table, fail

    EXCEPTION
        WHEN undefined_table THEN
            SELECT * INTO row FROM exceptions WHERE id = 1; -- get your exception
            RAISE EXCEPTION USING MESSAGE = row.message, DETAIL = row.detail, HINT = row.hint, ERRCODE = row.errcode;

    RETURN 1;
END;
$$

SELECT foo();

      



In any case, you can also hardcode them in your procedures, it's up to you.

+7


a source







All Articles