PostgreSQL custom exception conditions

旧巷老猫 提交于 2020-07-08 04:32:09

问题


Is it possible to create custom conditions when I raise an exception? Consider the following example:

BEGIN       
    y := x / 0;
EXCEPTION
    WHEN division_by_zero THEN
        RAISE NOTICE 'caught division_by_zero';
        RETURN x;
END;

Here I use 'division_by_zero' condition to catch the exception. What I'd like to do is something like this:

BEGIN       
    [...]
    RAISE custom_condition;
EXCEPTION
    WHEN custom_condition THEN
       [...]
END;

so that I don't interfere with possible standard exceptions. I could just do y:= 1 / 0; and catch division_by_zero, but it does not look right.


回答1:


begin
    if $1='bar' then
        raise exception using
            errcode='NOBAR',
            message='Bar is prohibited',
            hint='We do not talk to this guy';
    end if;
exception
    when sqlstate 'NOBAR' then
        update nobar_raised set count=count+1;
end;

More info:

  • Errors and Messages

  • Trapping Errors



来源:https://stackoverflow.com/questions/7767413/postgresql-custom-exception-conditions

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