PostgreSQL 自定义异常条件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7767413/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-20 23:22:12  来源:igfitidea点击:

PostgreSQL custom exception conditions

postgresqlexceptionexception-handlingconditional-statementscustom-exceptions

提问by Snifff

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:

在这里,我使用 'division_by_zero' 条件来捕获异常。我想做的是这样的:

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.

这样我就不会干扰可能的标准例外。我可以做 y:= 1 / 0;并捕获 Division_by_zero,但它看起来不正确。

回答by Tometzky

begin
    if ='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:

更多信息: