php錯誤及異常捕捉

傑克.陳發表於2014-12-10
原文:
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),配合使用。

<?php
// we will do our own error handling
error_reporting(0);
function userErrorHandler($errno, $errmsg, $filename, $linenum, $vars)
{
    // timestamp for the error entry    
	$dt = date("Y-m-d H:i:s (T)");    
	// define an assoc array of error string    
	// in reality the only entries we should    
	// consider are E_WARNING, E_NOTICE, E_USER_ERROR,    
	// E_USER_WARNING and E_USER_NOTICE    
	$errortype = array (                
		E_ERROR              => `Error`,                
		E_WARNING            => `Warning`,                
		E_PARSE              => `Parsing Error`,                
		E_NOTICE             => `Notice`,                
		E_CORE_ERROR         => `Core Error`,                
		E_CORE_WARNING       => `Core Warning`,                
		E_COMPILE_ERROR      => `Compile Error`,                
		E_COMPILE_WARNING    => `Compile Warning`,                
		E_USER_ERROR         => `User Error`,                
		E_USER_WARNING       => `User Warning`,                
		E_USER_NOTICE        => `User Notice`,                
		E_STRICT             => `Runtime Notice`,                
		E_RECOVERABLE_ERROR  => `Catchable Fatal Error`                
	);    
	// set of errors for which a var trace will be saved    
	$user_errors = array(E_USER_ERROR, E_USER_WARNING, E_USER_NOTICE);        
	$err = "<errorentry>
";    
	$err .= "	<datetime>" . $dt . "</datetime>
";    
	$err .= "	<errornum>" . $errno . "</errornum>
";    
	$err .= "	<errortype>" . $errortype[$errno] . "</errortype>
";    
	$err .= "	<errormsg>" . $errmsg . "</errormsg>
";    
	$err .= "	<scriptname>" . $filename . "</scriptname>
";    
	$err .= "	<scriptlinenum>" . $linenum . "</scriptlinenum>
";    
	if (in_array($errno, $user_errors)) {        
		$err .= "	<vartrace>" . wddx_serialize_value($vars, "Variables") . "</vartrace>
";    
	}    
	$err .= "</errorentry>

";
	echo $err;
}
function distance($vect1, $vect2) {    
	if (!is_array($vect1) || !is_array($vect2)) {        
		trigger_error("Incorrect parameters, arrays expected", E_USER_ERROR);        
		return NULL;    
	}    
	if (count($vect1) != count($vect2)) {        
		trigger_error("Vectors need to be of the same size", E_USER_ERROR);        
		return NULL;    
	} 
	for ($i=0; $i<count($vect1); $i++) {        
		$c1 = $vect1[$i]; $c2 = $vect2[$i];        
		$d = 0.0;        
		if (!is_numeric($c1)) {            
		trigger_error("Coordinate $i in vector 1 is not a number, using zero",E_USER_WARNING);            
		$c1 = 0.0;        
	}        
	if (!is_numeric($c2)) {            
		trigger_error("Coordinate $i in vector 2 is not a number, using zero",E_USER_WARNING);            
		$c2 = 0.0;        
	}
	$d += $c2*$c2 - $c1*$c1;    
	}    
	return sqrt($d);
}

$old_error_handle = set_error_handler("userErrorHandler");
$t = I_AM_NOT_DEFINED;	//generates a warning

// define some "vectors"
$a = array(2, 3, "foo");
$b = array(5.5, 4.3, -1.6);
$c = array(1, -3);

//generate a user error
$t1 = distance($c,$b);

// generate another user error
$t2 = distance($b, "i am not an array") . "
";

// generate a warning
$t3 = distance($a, $b) . "
";
?>

 

b)   set_exception_handler
設定預設的異常處理程式,用於沒有用 try/catch 塊來捕獲的異常。 在 exception_handler 呼叫後異常會中止。
與throw new Exception(`Uncaught Exception occurred`),連用。

<?php
// we will do our own error handling
error_reporting(0);
function exceptHandle($errno, $errmsg, $filename, $linenum, $vars)
{
    // timestamp for the error entry    
	$dt = date("Y-m-d H:i:s (T)");    
	// define an assoc array of error string    
	// in reality the only entries we should    
	// consider are E_WARNING, E_NOTICE, E_USER_ERROR,    
	// E_USER_WARNING and E_USER_NOTICE    
	$errortype = array (                
		E_ERROR              => `Error`,                
		E_WARNING            => `Warning`,                
		E_PARSE              => `Parsing Error`,                
		E_NOTICE             => `Notice`,                
		E_CORE_ERROR         => `Core Error`,                
		E_CORE_WARNING       => `Core Warning`,                
		E_COMPILE_ERROR      => `Compile Error`,                
		E_COMPILE_WARNING    => `Compile Warning`,                
		E_USER_ERROR         => `User Error`,                
		E_USER_WARNING       => `User Warning`,                
		E_USER_NOTICE        => `User Notice`,                
		E_STRICT             => `Runtime Notice`,                
		E_RECOVERABLE_ERROR  => `Catchable Fatal Error`                
	);    
	// set of errors for which a var trace will be saved    
	$err = "<errorentry>
";    
	$err .= "	<datetime>" . $dt . "</datetime>
";    
	$err .= "	<errornum>" . $errno . "</errornum>
";    
	$err .= "	<errortype>" . $errortype[$errno] . "</errortype>
";    
	$err .= "	<errormsg>" . $errmsg . "</errormsg>
";    
	$err .= "	<scriptname>" . $filename . "</scriptname>
";    
	$err .= "	<scriptlinenum>" . $linenum . "</scriptlinenum>
";    
	if (1) {        
		$err .= "	<vartrace>" . wddx_serialize_value($vars, "Variables") . "</vartrace>
";    
	}    
	$err .= "</errorentry>

";
	echo $err;
}
$old_except_handle = set_exception_handler("exceptHandle");
//$t = I_AM_NOT_DEFINED;	//generates a warning
$a;
throw new Exception(`Uncaught Exception occurred`);    
?>

 

c)   register_shutdown_function
執行機制是:php把要呼叫的函式調入記憶體。當頁面所有PHP語句都執行完成時,再呼叫此函式。
一般與trigger_error(“…”, E_USER_ERROR),配合使用。

<?php
error_reporting(0);
date_default_timezone_set(`Asia/Shanghai`);
register_shutdown_function(`my_exception_handler`);

$t = I_AM_NOT_DEFINED;	//generates a warning
trigger_error("Vectors need to be of the same size", E_USER_ERROR);     

function my_exception_handler()
{
    if($e = error_get_last()) {
    //$e[`type`]對應php_error常量
    $message = ``;
    $message .= "出錯資訊:	".$e[`message`]."

";
    $message .= "出錯檔案:	".$e[`file`]."

";
    $message .= "出錯行數:	".$e[`line`]."

";
    $message .= "		請工程師檢查出現程式".$e[`file`]."出現錯誤的原因
";
    $message .= "		希望能您早點解決故障出現的原因<br/>";
	echo $message;
    //sendemail to
    }
}
?>

c) restore_error_handler()函式

定義和用法 restore_error_handler() 函式恢復之前的錯誤處理程式,該程式是由 set_error_handler() 函式改變的。

該函式永遠返回 true。

set_error_handler()的反函式。


相關文章