PostgreSQL custom exceptions?

天大地大妈咪最大 提交于 2019-12-21 05:57:24

问题


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 stored procedures, we can raise the exception like so:

EXCEPTION EXP_CUSTOM_0 ;

Is there an equivalent in PostgreSQL ?


回答1:


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.



来源:https://stackoverflow.com/questions/2699958/postgresql-custom-exceptions

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!