php错误及异常捕捉

在实际开发中,错误及异常捕捉仅仅靠try{}catch()是远远不够的。
所以引用以下几中函数。
a)   set_error_handler
一般用于捕捉  E_NOTICE 、E_USER_ERROR、E_USER_WARNING、E_USER_NOTICE
不能捕捉:
E_ERROR, E_PARSE, E_CORE_ERROR, E_CORE_WARNING, E_COMPILE_ERROR and E_COMPILE_WARNING。
一般与trigger_error("...", E_USER_ERROR),配合使用。

  1. <?php  
  2. // we will do our own error handling  
  3. error_reporting(0);  
  4. function userErrorHandler($errno$errmsg$filename$linenum$vars)  
  5. {  
  6.     // timestamp for the error entry      
  7.     $dt = date("Y-m-d H:i:s (T)");      
  8.     // define an assoc array of error string      
  9.     // in reality the only entries we should      
  10.     // consider are E_WARNING, E_NOTICE, E_USER_ERROR,      
  11.     // E_USER_WARNING and E_USER_NOTICE      
  12.     $errortype = array (                  
  13.         E_ERROR              => 'Error',                  
  14.         E_WARNING            => 'Warning',                  
  15.         E_PARSE              => 'Parsing Error',                  
  16.         E_NOTICE             => 'Notice',                  
  17.         E_CORE_ERROR         => 'Core Error',                  
  18.         E_CORE_WARNING       => 'Core Warning',                  
  19.         E_COMPILE_ERROR      => 'Compile Error',                  
  20.         E_COMPILE_WARNING    => 'Compile Warning',                  
  21.         E_USER_ERROR         => 'User Error',                  
  22.         E_USER_WARNING       => 'User Warning',                  
  23.         E_USER_NOTICE        => 'User Notice',                  
  24.         E_STRICT             => 'Runtime Notice',                  
  25.         E_RECOVERABLE_ERROR  => 'Catchable Fatal Error'                  
  26.     );      
  27.     // set of errors for which a var trace will be saved      
  28.     $user_errors = array(E_USER_ERROR, E_USER_WARNING, E_USER_NOTICE);          
  29.     $err = "<errorentry>\n";      
  30.     $err .= "\t<datetime>" . $dt . "</datetime>\n";      
  31.     $err .= "\t<errornum>" . $errno . "</errornum>\n";      
  32.     $err .= "\t<errortype>" . $errortype[$errno] . "</errortype>\n";      
  33.     $err .= "\t<errormsg>" . $errmsg . "</errormsg>\n";      
  34.     $err .= "\t<scriptname>" . $filename . "</scriptname>\n";      
  35.     $err .= "\t<scriptlinenum>" . $linenum . "</scriptlinenum>\n";      
  36.     if (in_array($errno$user_errors)) {          
  37.         $err .= "\t<vartrace>" . wddx_serialize_value($vars"Variables") . "</vartrace>\n";      
  38.     }      
  39.     $err .= "</errorentry>\n\n";  
  40.     echo $err;  
  41. }  
  42. function distance($vect1$vect2) {      
  43.     if (!is_array($vect1) || !is_array($vect2)) {          
  44.         trigger_error("Incorrect parameters, arrays expected", E_USER_ERROR);          
  45.         return NULL;      
  46.     }      
  47.     if (count($vect1) != count($vect2)) {          
  48.         trigger_error("Vectors need to be of the same size", E_USER_ERROR);          
  49.         return NULL;      
  50.     }   
  51.     for ($i=0; $i<count($vect1); $i++) {          
  52.         $c1 = $vect1[$i]; $c2 = $vect2[$i];          
  53.         $d = 0.0;          
  54.         if (!is_numeric($c1)) {              
  55.         trigger_error("Coordinate $i in vector 1 is not a number, using zero",E_USER_WARNING);              
  56.         $c1 = 0.0;          
  57.     }          
  58.     if (!is_numeric($c2)) {              
  59.         trigger_error("Coordinate $i in vector 2 is not a number, using zero",E_USER_WARNING);              
  60.         $c2 = 0.0;          
  61.     }  
  62.     $d += $c2*$c2 - $c1*$c1;      
  63.     }      
  64.     return sqrt($d);  
  65. }  
  66.   
  67. $old_error_handle = set_error_handler("userErrorHandler");  
  68. $t = I_AM_NOT_DEFINED;  //generates a warning  
  69.   
  70. // define some "vectors"  
  71. $a = array(2, 3, "foo");  
  72. $b = array(5.5, 4.3, -1.6);  
  73. $c = array(1, -3);  
  74.   
  75. //generate a user error  
  76. $t1 = distance($c,$b);  
  77.   
  78. // generate another user error  
  79. $t2 = distance($b"i am not an array") . "\n";  
  80.   
  81. // generate a warning  
  82. $t3 = distance($a$b) . "\n";  
  83. ?>  

 

b)   set_exception_handler 
设置默认的异常处理程序,用于没有用 try/catch 块来捕获的异常。 在 exception_handler 调用后异常会中止。 
与throw new Exception('Uncaught Exception occurred'),连用。

  1. <?php  
  2. // we will do our own error handling  
  3. error_reporting(0);  
  4. function exceptHandle($errno$errmsg$filename$linenum$vars)  
  5. {  
  6.     // timestamp for the error entry      
  7.     $dt = date("Y-m-d H:i:s (T)");      
  8.     // define an assoc array of error string      
  9.     // in reality the only entries we should      
  10.     // consider are E_WARNING, E_NOTICE, E_USER_ERROR,      
  11.     // E_USER_WARNING and E_USER_NOTICE      
  12.     $errortype = array (                  
  13.         E_ERROR              => 'Error',                  
  14.         E_WARNING            => 'Warning',                  
  15.         E_PARSE              => 'Parsing Error',                  
  16.         E_NOTICE             => 'Notice',                  
  17.         E_CORE_ERROR         => 'Core Error',                  
  18.         E_CORE_WARNING       => 'Core Warning',                  
  19.         E_COMPILE_ERROR      => 'Compile Error',                  
  20.         E_COMPILE_WARNING    => 'Compile Warning',                  
  21.         E_USER_ERROR         => 'User Error',                  
  22.         E_USER_WARNING       => 'User Warning',                  
  23.         E_USER_NOTICE        => 'User Notice',                  
  24.         E_STRICT             => 'Runtime Notice',                  
  25.         E_RECOVERABLE_ERROR  => 'Catchable Fatal Error'                  
  26.     );      
  27.     // set of errors for which a var trace will be saved      
  28.     $err = "<errorentry>\n";      
  29.     $err .= "\t<datetime>" . $dt . "</datetime>\n";      
  30.     $err .= "\t<errornum>" . $errno . "</errornum>\n";      
  31.     $err .= "\t<errortype>" . $errortype[$errno] . "</errortype>\n";      
  32.     $err .= "\t<errormsg>" . $errmsg . "</errormsg>\n";      
  33.     $err .= "\t<scriptname>" . $filename . "</scriptname>\n";      
  34.     $err .= "\t<scriptlinenum>" . $linenum . "</scriptlinenum>\n";      
  35.     if (1) {          
  36.         $err .= "\t<vartrace>" . wddx_serialize_value($vars"Variables") . "</vartrace>\n";      
  37.     }      
  38.     $err .= "</errorentry>\n\n";  
  39.     echo $err;  
  40. }  
  41. $old_except_handle = set_exception_handler("exceptHandle");  
  42. //$t = I_AM_NOT_DEFINED;    //generates a warning  
  43. $a;  
  44. throw new Exception('Uncaught Exception occurred');      
  45. ?>  

 

c)   register_shutdown_function 
执行机制是:php把要调用的函数调入内存。当页面所有PHP语句都执行完成时,再调用此函数。
一般与trigger_error("...", E_USER_ERROR),配合使用。

  1. <?php  
  2. error_reporting(0);  
  3. date_default_timezone_set('Asia/Shanghai');  
  4. register_shutdown_function('my_exception_handler');  
  5.   
  6. $t = I_AM_NOT_DEFINED;  //generates a warning  
  7. trigger_error("Vectors need to be of the same size", E_USER_ERROR);       
  8.   
  9. function my_exception_handler()  
  10. {  
  11.     if($e = error_get_last()) {  
  12.     //$e['type']对应php_error常量  
  13.     $message = '';  
  14.     $message .= "出错信息:\t".$e['message']."\n\n";  
  15.     $message .= "出错文件:\t".$e['file']."\n\n";  
  16.     $message .= "出错行数:\t".$e['line']."\n\n";  
  17.     $message .= "\t\t请工程师检查出现程序".$e['file']."出现错误的原因\n";  
  18.     $message .= "\t\t希望能您早点解决故障出现的原因<br/>";  
  19.     echo $message;  
  20.     //sendemail to  
  21.     }  
  22. }  
  23. ?>  

c) restore_error_handler()函数

定义和用法 restore_error_handler() 函数恢复之前的错误处理程序,该程序是由 set_error_handler() 函数改变的。

该函数永远返回 true。

 set_error_handler()的反函数。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值