Oracle PL/SQL数据库:如何将异常传递到过程中

wko9yo5t  于 2022-11-03  发布在  Oracle
关注(0)|答案(1)|浏览(151)

是否有一种方法可以将异常传递到一个过程中,以便在执行了一些处理异常的操作之后调用“raise”。这样外部代码块就可以获得所引发的准确异常
大概是这样的:

begin
    ...
exception
    when others then
        error_handler( err );
end;

procedure error_handler ( err ) is
begin
    /*
        here some code to handle and log the exception...
    */

    raise err;
end;

或者唯一的方法是将SQLCODE和SQLERRM传递到过程中,然后调用raise_application_error(SQLCODE,SQLERRM)?

s5a0g9ez

s5a0g9ez1#

如果我没理解错的话,这就是你要问的。
示例日志表:

SQL> create table err_log
  2    (program    varchar2(30),
  3     datum      date,
  4     sqlcode    number
  5    );

Table created.

日志记录过程应该是一个自治的事务,这样你就可以在其中commit,而不影响主事务。

SQL> create or replace procedure error_handler
  2    (p_program in varchar2, p_sqlcode in number)
  3  is
  4    pragma autonomous_transaction;
  5  begin
  6    insert into err_log (program, datum, sqlcode)
  7      values (p_program, sysdate, p_sqlcode);
  8    commit;
  9  end;
 10  /

Procedure created.

另一个过程(您正在记录其执行);它将引发 division by zero。请参见第8行和第9行,它们调用日志记录过程,然后重新引发错误:

SQL> create or replace procedure p_test is
  2    l_program varchar2(30) := 'P_TEST';
  3    l_value   number;
  4  begin
  5    l_value := 1 / 0;
  6  exception
  7    when others then
  8      error_handler(l_program, sqlcode);
  9      raise;
 10  end p_test;
 11  /

Procedure created.

好了,一切都准备好了。我们来试试:

SQL> exec p_test;
BEGIN p_test; END;

* 

ERROR at line 1:
ORA-01476: divisor is equal to zero         --> this is result of RAISE in line #9
ORA-06512: at "SCOTT.P_TEST", line 9
ORA-06512: at "SCOTT.P_TEST", line 5
ORA-06512: at line 1

日志表内容:

SQL> select * from err_log;

PROGRAM                        DATUM                  SQLCODE
------------------------------ ------------------- ----------
P_TEST                         01.11.2022 11:13:31      -1476

SQL>

你问,随便:
如何将异常传递到过程中?
就我所知,你不能:

SQL> create or replace procedure error_handler_text
  2    (p_err in exception)                  --> if this is what you asked
  3  is
  4  begin
  5    null;
  6  end;
  7  /

Warning: Procedure created with compilation errors.

SQL> show err
Errors for PROCEDURE ERROR_HANDLER_TEXT:

LINE/COL ERROR
-------- -----------------------------------------------------------------
2/13     PLS-00103: Encountered the symbol "EXCEPTION" when expecting one
         of the following:
         out <an identifier> <a double-quoted delimited-identifier>
         table columns long double ref char standard time timestamp
         interval date binary national character nchar
         The symbol "<an identifier> was inserted before "EXCEPTION" to
         continue.

SQL>

相关问题