【问题标题】:How does one report the line on which an error occured in Postgres/plpgsql?如何报告 Postgres/plpgsql 中发生错误的行?
【发布时间】:2015-06-03 22:15:55
【问题描述】:

我在 postgres 中或多或少地使用了类似的东西来模拟在 SQL Server 中我如何使用 Try/Catch 块以及在发现错误时可以在 Catch 中回滚的事务:

do $$
begin
[SQL here]

exception when others then
    raise notice 'Error in insert statement ---> % %', SQLERRM, SQLSTATE LINE;
end;    

$$ language 'plpgsql';

有没有办法报告发生错误的行,例如“ERROR_LINE()”?

提前致谢

【问题讨论】:

    标签: postgresql error-handling plpgsql


    【解决方案1】:

    在某些现代 PostgreSQL 上,您可以使用 GET STACKED DIAGNOSTICS 语句。无法获取 linenumber,但您可以获得包含 lineno 的调用上下文:

    postgres=> DO $$
    DECLARE 
      a int DEFAULT 0;
      _c text;
    BEGIN
      BEGIN
        PERFORM 10/a;
      EXCEPTION WHEN OTHERS THEN
        GET STACKED DIAGNOSTICS _c = PG_EXCEPTION_CONTEXT;
        RAISE NOTICE 'context: >>%<<', _c;
      END;
    END;
    $$;
    NOTICE:  00000: context: >>SQL statement "SELECT 10/a"
    PL/pgSQL function inline_code_block line 7 at PERFORM<<
    LOCATION:  exec_stmt_raise, pl_exec.c:3041
    DO
    

    【讨论】:

    • 大家都知道。这仅适用于 9.2 及更高版本。我什至确认它不适用于 9.1
    【解决方案2】:
    DO $$
    DECLARE 
    a int DEFAULT 0;
          m_sqlstate text;
          m_message text;
          m_context text;
          m_PG_EXCEPTION_HINT text;
    BEGIN
          PERFORM 10/a;
          EXCEPTION WHEN OTHERS THEN
    GET STACKED DIAGNOSTICS
          m_sqlstate = returned_sqlstate,
          m_message = message_text,
          m_context = pg_exception_context,
          m_PG_EXCEPTION_HINT = PG_EXCEPTION_HINT;
             RAISE NOTICE 'sqlstate: %', m_sqlstate; --show for error code .
             RAISE NOTICE 'message: %', m_message;
             RAISE NOTICE 'context: %', m_context;
             RAISE NOTICE 'The exception detail: %', m_PG_EXCEPTION_HINT;
    END
    $$;
    

    结果:

    NOTICE:  sqlstate: 22012
    NOTICE:  message: division by zero
    NOTICE:  context: SQL statement "SELECT 10/a"
    PL/pgSQL function inline_code_block line 9 at PERFORM
    NOTICE:  The exception detail:
    DO
    
    • 手动reference 用于获取诊断堆栈。特别检查 表 43.2。错误诊断项
    • PostgreSQL 错误代码在手册appendix 中,这不容易 找到。

    如您所见:pg_exception_context 将报告发生的行。 在 PostgreSQL 版本:14

    上测试

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-11-04
      • 1970-01-01
      • 2015-05-12
      • 1970-01-01
      • 1970-01-01
      • 2018-11-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多