Using a pl/sql procedure to log errors and handle exceptions

时间:2015-09-14 15:53:43

标签: oracle stored-procedures plsql error-handling

so far stack overflow and the oracle forums and docs have been my best friend in learning PLSQL. I'm running into an issue here. Any advice is appreciated. I'm writing a procedure that would be used to log any errors a package may encounter and log them into the error log table I created. here is my code thus far.

CREATE OR REPLACE PROCEDURE APMS.test_procedure AS

    procedure write_error_log (errcode number, errstr varchar2, errline varchar2) is
    pragma autonomous_transaction; 
    -- this procedure stays in its own new private transaction
    begin                         
          INSERT INTO error_log
               (ora_err_tmsp,
                      ora_err_number,
                      ora_err_msg,
                      ora_err_line_no)
          values (CURRENT_TIMESTAMP,
                  errcode,
                  errstr,
                  errline);
          COMMIT;  -- this commit does not interfere with the caller's transaction.
    end write_error_log;

 BEGIN
    INSERT INTO mockdata
        VALUES ('data1', 'mockname', 'mockcity'); 

  exception when others then             
    write_error_log(sqlcode,sqlerrm,dbms_utility.format_error_backtrace);
    raise; 
 END test_procedure;
/

In the procedure I currently am using a mockdata table to induce an invalid number error and log that to the error_log table. At this point the error log table proves to be functional and inserts the data needed. The next step for me is to use this procedure to be used in the exception handlers in other programs so that the error is caught and logged to the table. Currently, my procedure is only unique to the mock_data table. My mentor/superior is telling me I need to pass this program some parameters to use it in other packages and exception handlers. I'm just having a bit of trouble. Any help would be appreciated thank you!

2 个答案:

答案 0 :(得分:1)

首先,你应该让你的来电者通过errline。这非常乏味!当开发人员需要插入一行或两行代码时会发生什么?他们是否需要在该点之后更新对write_error_log的每次通话以更新行号?您的write_error_log应该使用dbms_utility.format_call_stack(或12c更方便的变体......不要使其名称方便)来确定调用write_error_log的代码行

然后,你应该有一个名为write_exception的第二个程序。所有需要做的就是这样:

write_error_log (SQLCODE, SUBSTR (DBMS_UTILITY.format_error_stack || DBMS_UTILITY.format_error_backtrace, 1, 4000));

答案 1 :(得分:1)

Steven Feuerstein在Oracle Magazine上撰写了几篇关于如何处理PLSQL错误的文章。他提供了一个小框架(errpkg)来做到这一点。 DRY原则(不要重复自己)是他的口头禅!

https://resources.oreilly.com/examples/0636920024859/blob/master/errpkg.pkg