ORACLE 存儲過程當中保存用戶自定義異常信息的一種方式

1.建立錯誤日誌表:node

create table REP_LOGS
(
  log_s_no NUMBER not null,
  log_date DATE default sysdate not null,
  log_type VARCHAR2(1) default 'E' not null,
  log_node VARCHAR2(60) not null,
  log_mesg VARCHAR2(300) not null
);

-- Add comments to the table 
comment on table REP_LOGS
  is '系統操做日誌信息表';
-- Add comments to the columns 
comment on column REP_LOGS.log_s_no
  is '日誌序列號 由序列SEQ_REP_LOGS生成';
comment on column REP_LOGS.log_date
  is '日誌時間';
comment on column REP_LOGS.log_type
  is '日誌類型 ''E'':異常(默認);''N'':正常;''W'':警告';
comment on column REP_LOGS.log_node
  is '寫入日誌的節點';
comment on column REP_LOGS.log_mesg
  is '詳細信息';

2.建立用於向上述日誌表中寫數據的存儲過程(獨立事物)sql

create or replace procedure p_messagelogging(str_i_logtype in varchar2,
                                                 str_i_lognode in varchar2,
                                                 str_i_logmesg in varchar2) 
/*************************************************************************
**    Name :      p_messagelogging
**    Purpose :   記錄日誌
*************************************************************************/
is
    pragma autonomous_transaction;
begin
    insert into rep_logs(log_s_no, log_type, log_node, log_mesg)
    values(seq_rep_logs.nextval, str_i_logtype, str_i_lognode, str_i_logmesg);
    commit;
end p_messagelogging;

3.在存儲過程當中捕獲異常並使用上述存儲過程記錄錯誤信息。spa

create or replace procedure p_myproc(arg1 in number, arg2 in varchar2)
is
     str_l_errmsg rep_logs.log_mesg%type; --異常信息
    str_l_errloc varchar2(30);
begin
     str_l_errloc:='my mark 1';
     .....
     str_l_errloc:='my mark 2';
exception
     when others then
     str_l_errmsg := substrb('Tips:'||str_l_errloc || '-' || sqlerrm, 1, 300);
     p_messagelogging('error type', 'current procedure name', str_l_errmsg);
     raise;
end p_myproc;

經過這種方式(再配合自定義異常),能夠在程序出錯的時候,根據日誌表查找出出錯的存儲過程名以及詳細代碼位置,特別是在存儲過程嵌套調用層次很深的時候,上述處理方式會頗有用,這也是ORACLE自治事物最經常使用的場合。日誌

相關文章
相關標籤/搜索