Oracle存储过程中的异常处理

[转]Oracle存储过程中的异常处理

                                      

1.问题来源
Oracle中可以用dbms_output.put_line来打印提示信息,但是很容易缓冲区就溢出了。
可以用DBMS_OUTPUT.ENABLE(1000000);来设置缓冲区的大小。
但是有大小,就有可能再溢出(程序写得太烂,错误不断,不好意思)。
于是想把异常信息写到一个表中。
2.建表
这个容易
create table wErrorLog
(
  procedure_name varchar2(50) not null
 ,err_msg        varchar2(255) not null
 ,sys_err_code   varchar2(10) not null
 ,sys_err_msg   varchar2(1000) not null
 ,create_time     date         not null
);
comment on table wErrorLog is 'log表,用于记录存储过程的错误';
comment on column wErrorLog.procedure_name is '过程名,出错的存储过程或函数';
comment on column wErrorLog.err_msg is '自定义出错信息';
comment on column wErrorLog.sys_err_code is 'Oracle系统的出错代码';
comment on column wErrorLog.sys_err_msg is 'Oracle系统的出错信息';
comment on column wErrorLog.create_time is '错误发生时间';
3.存储过程
CREATE OR REPLACE PROCEDURE prc_err_log
(
 i_procedure_name Varchar2
,i_err_msg        Varchar2
)
--写日志的过程,Albert Song 2005-06-28
--注意本过程没有进行commit或rollback操作
--用法
--Exception
--   WHEN OTHERS
--   Then
--      rollbak;
--      prc_err_log('prc_err_log','写日志表错误');
--      commit;
As
v_sqlcode Varchar(10);
v_sqlerrm Varchar(1000);
Begin
  v_sqlcode:=Sqlcode;
  v_sqlerrm:=Sqlerrm;
  Insert Into wErrorLog Values(i_procedure_name,i_err_msg,v_sqlcode,v_sqlerrm,Sysdate);
  Exception
   WHEN OTHERS
   Then
      v_sqlcode:=Sqlcode;
      v_sqlerrm:=Sqlerrm;
      Insert Into wErrorLog Values('prc_err_log','写日志表错误',v_sqlcode,v_sqlerrm,Sysdate);
END;
4.使用
create or replace procedure prc_test
As
v_data varchar2(255);
Begin
  Insert Into wErrorLog Values('prc,'错误','test','test',Sysdate);
  Select err_msg Into v_data from wErrorLog  where err_msg='no err msg';
  Exception
  When Others Then
  Rollback;
  prc_err_log('prc_test','测试prc_err_log');
  Commit;
  
end ;
5.测试
exec prc_test;
select * from wErrorLog;
6.说明
为什么不能在prc_err_log中commit?
目的是可以用在这样的地方
create or replace procedure prc_test_transaction
As
v_in Varchar2(255);
begin
  Insert Into testsql Values('11','55');
  If 1=1 Then 
  begin
            Select code Into v_in From testsql Where code='12323';
            exception
           when others  
           then 
             prc_err_log('prc_test_transaction','testsql表中不存在code为12323的记录');
      
            end;
 END IF;
 ...
 commit;
 
  Exception
   WHEN OTHERS
   Then
      rollback;
      prc_err_log('prc_err_log','出现了未知的错误');
      commit;
end ;
这种情况下,如果在第一个prc_err_log处commit会将已经执行的操作提交了。

后记:
我的目的只有一个,就是详细地记录程序的运行过程,最好是能知道哪一行程序出了异常。现在可以在err_msg里记录一些自定义的变量来跟踪程序状态了。
刚学Oracle不久,我觉得应该有更好的方法,但是我没有找到,自己也没有创造出来。
dbms_output有个new_line不知是不是可以防止缓冲区溢出呢? 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值