php error handling

今天來研究一下 php 的 error handling, 一般的程式錯誤, 很重要的一件事就是錯誤處理, php 當然也不例外. php 本身對於錯誤處理已有一套完整的設計, 讓程式設計人員可以很容易地進行錯誤處理.

我們可以參考內建 function 進行 error handler 設置, 這個 function 為 :
mixed set_error_handler ( callback error_handler [, int error_types] )

該 function 傳入的 callback function即為我們要使用的 error handling function, 該 function 定義如下:
handler ( int errno, string errstr [, string errfile [, int errline [, array errcontext]]] )

分別對於上面的幾個參數說明:
error_types 此參數為一個過濾器, 用來處理要處理的 error型態, php 5 以上始支援.
errorno 為 error level.
errstr 為 error 的描述.
errfile 為發生錯誤的檔案名稱.
errline 為發生錯誤的行數.
errcontext 則是用來存放在該錯誤發生時的該scope下的變數內容

而 set_error_handler 回傳值則為前一個 error handler 的 call back function(若有的話).

實務上通常只對 handler 前面 4 個參數比較有具體用處, 可以方便程式設計人員進行除錯使用, 對於 debug 或偵測錯誤發生而做處理是很有參考價值的.

而回復為前一個 error handler 則是利用另一個 function 達成:
bool restore_error_handler ( void )

總合以上所述, 要做一個簡單的錯誤處理可以這麼寫:

<?php
  
function myerror_handler ($error_level, $error_message, $file, $line) {
   echo "error_level=".$error_level."<br>";
   echo "error_message=".$error_message."<br>";
   echo "file=".$file."<br>";
   echo "line=".$line."<br>";           
}   
  
  
set_error_handler ('myerror_handler');   

$a=5;
$b=$a-5.0;
$c=1/$b;
echo $c;

trigger_error ('Trigger error was called with a simple error message');
trigger_error ('Trigger a warning', E_USER_WARNING);   

?>

執行後畫面如下:

error_level=2
error_message=Division by zero
file=g:\tools\errhandle.php
line=15
error_level=1024
error_message=Trigger error was called with a simple error message
file=g:\tools\errhandle.php
line=18
error_level=512
error_message=Trigger a warning
file=g:\tools\errhandle.php
line=19

可以很清楚地看到發生錯誤的說明及行數, 這對於除錯來說是非用有用的, 再加上 log 或是 email 通知, 就可以很方便地進行 php 的問題通知囉 (當然錯誤是不能發生在 log 或 email 這段 code 上面啦)

參考資料:
http://tw.php.net/manual/tw/function.set-error-handler.php
http://www.phpdig.net/ref/rn19re268.html
http://www.zend.com/zend/spotlight/error.php

另外到了 php 5 的版本, 還可以利用像是 c 語言的 try catch 語法進行錯誤的補捉, 在發生錯誤時直接進行 catch, 可以參考:
http://www.ugia.cn/manual/zh/language.exceptions.php

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *