开发者

PostgreSQL custom exceptions?

In Firebird we can declare custom exceptions like so:

CREATE EXCEPTION EXP_CUSTOM_0 'Exception: Custom exception';

these are stored at the database level. In sto开发者_开发百科red procedures, we can raise the exception like so:

EXCEPTION EXP_CUSTOM_0 ;

Is there an equivalent in PostgreSQL ?


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();

Offcourse you can also have them hardcoded in your procedures, that's up to you.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜