如何从RAISED异常中获取oracle PL / SQL中原始异常的堆栈跟踪?

时间:2016-11-30 17:31:30

标签: oracle exception plsql raise

我遇到一个问题,当我捕获异常时原始堆栈跟踪丢失,然后提升它。

  1. 在proc_a
  2. 中抛出异常
  3. 抓住例外。
  4. 执行回滚。
  5. 提出异常。
  6. 捕获异常(父块)
  7. 打印堆栈跟踪:SUBSTR(SQLERRM || chr(10) || DBMS_UTILITY.FORMAT_ERROR_BACKTRACE(), 1, 3999)
  8. 实施例

    DECLARE
    BEGIN
       DECLARE
          lv_val VARCHAR2(1);
       BEGIN
          SELECT dummy INTO lv_val -- Line# 6 (desired)
          FROM   dual
          WHERE  dummy = 'FFF';
       EXCEPTION
          WHEN OTHERS THEN
             --DBMS_OUTPUT.PUT_LINE(SUBSTR(SQLERRM || chr(10) || DBMS_UTILITY.FORMAT_ERROR_BACKTRACE(), 1, 3999));
             RAISE; -- Line# 12 (actual)
       END;
    EXCEPTION
       WHEN OTHERS THEN
          DBMS_OUTPUT.PUT_LINE(SUBSTR(SQLERRM || chr(10) || DBMS_UTILITY.FORMAT_ERROR_BACKTRACE(), 1, 3999));
    END;
    /
    

    期望的结果:

    原始例外的行号(步骤1)。

    ORA-01403: no data found
    ORA-06512: at line 6
    

    ORA-01403: no data found
    ORA-06512: at line 12
    Caused By:
    ORA-01403: no data found
    ORA-06512: at line 6
    

    实际结果:

    RAISE的行号(步骤4)。

    ORA-01403: no data found
    ORA-06512: at line 12
    

    失败的其他尝试:

    SQLERRM || chr(10) || DBMS_UTILITY.FORMAT_ERROR_STACK()

    ORA-01403: no data found
    ORA-01403: no data found
    

    SQLERRM || chr(10) || DBMS_UTILITY.FORMAT_CALL_STACK()

    ORA-01403: no data found
    ----- PL/SQL Call Stack -----
      object      line  object
      handle    number  name
    0xee1cbd68        18  anonymous block
    

1 个答案:

答案 0 :(得分:4)

在内部异常处理程序中,不使用RAISE过程,而是使用RAISE_APPLICATION_ERROR过程将dbms_utility.format_error_backtrace函数的结果传递给它以获取原始行号:

BEGIN
   DECLARE
      lv_val VARCHAR2(1);
   BEGIN
      SELECT dummy INTO lv_val -- Line# 6 (desired)
      FROM   dual
      WHERE  dummy = 'FFF';
   EXCEPTION
      WHEN OTHERS THEN
         RAISE_APPLICATION_ERROR(-20001, dbms_utility.format_error_backtrace,true);
   END;
EXCEPTION
   WHEN OTHERS THEN
      DBMS_OUTPUT.PUT_LINE(SUBSTR(SQLERRM || chr(10) || DBMS_UTILITY.FORMAT_ERROR_BACKTRACE(), 1, 3999));
END;
/

如果没有外部异常处理程序,您将收到以下错误报告:

Error report -
ORA-20001: ORA-06512: at line 5
ORA-06512: at line 10
ORA-01403: no data found

使用外部异常处理程序,您将获得以下内容:

ORA-20001: ORA-06512: at line 5
ORA-01403: no data found
ORA-06512: at line 10

消息排序略有不同,但信息仍然存在。