【问题标题】:PostgreSQL custom exception conditionsPostgreSQL 自定义异常条件
【发布时间】:2011-10-14 12:15:10
【问题描述】:

当我引发异常时,是否可以创建自定义条件? 考虑以下示例:

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

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

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

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

【问题讨论】:

    标签: postgresql exception exception-handling conditional-statements custom-exceptions


    【解决方案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;
    

    更多信息:

    【讨论】:

    • 谢谢!它可以进行一次更正 - errcode 参数应该正好是五位数字/大写 ASCII 字符,否则会导致错误 (invalid SQLSTATE code)。这是您链接中的注释:Note: When specifying an error code by SQLSTATE code, you are not limited to the predefined error codes, but can select any error code consisting of five digits and/or upper-case ASCII letters, other than 00000. It is recommended that you avoid throwing error codes that end in three zeroes, because these are category codes and can only be trapped by trapping the whole category.
    • @Sniff:谢谢 - 我已经更正了 errcode 字符的大小写
    • @Tometzky:在 exception.diagnostic 下的哪个属性下显示“禁止酒吧”?是 MESSAGE_TEXT 还是 PG_EXCEPTION_DETAIL 还是 PG_EXCEPTION_HINT? (文档:goo.gl/F5w1y
    猜你喜欢
    • 2011-02-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-03
    相关资源
    最近更新 更多