首页 > PHP > PHP中自定错误和异常处理函数

PHP中自定错误和异常处理函数

2009年4月16日

PHP 函数set_error_handler()的用法

<?PHP
function ErrorHandler($errno, $errmsg, $errfile, $errline) {
	if ($errno == E_USER_ERROR) {
		$msg = "<strong>Custom Error:</strong>$errmsg<br />\n";
		$msg .= "File:$errfile<br />\n";
		$msg .= "Line Number:$errline<br />\n";
	}
	echo $msg;
	// 记录错误信息
	error_log(date("[Y-m-d H:i:s]")." -[".$_SERVER['REQUEST_URI']."] :".$msg."\n", 3, 'log.txt');
//	exit(); // 必要时必须终止脚本执行.
}
 
// set_error_handler()函数用于让用户自定义错误处理函数
// set_error_handler(error_function, error_type)
// error_function 必须, 制定发生错误时运行的函数
// error_type 可选, 规定不同的错误级别提示的不同信息, 默认是"E_ALL"
set_error_handler('ErrorHandler');
 
$foo = 2;
if ($foo > 1) {
	// trigger_error()接收一个错误信息和一个常量作为参数, 
	// 常量为E_USER_ERROR -> a fatal error
	//		 E_USER_WARNING -> a non-fatal error
	//		 E_USER_NOTICE -> a report that may not represent an error 
	trigger_error("A custom error has been trigglered", E_USER_ERROR);
}
?>

PHP 函数set_exception_handler()的用法

<?php
function ExceptionHandler($e) {
	echo "<strong>Exception:</strong>".$e->getMessage();
	echo "Stack Trace String:".$e->getTraceAsString();
}
 
// set_exception_handler()函数用于让用户自定义异常处理函数
// set_exception_handler(exception_function)
// 该函数需要抛出的exception对象最为参数
// 在这个异常处理程序被执行后, 脚本会停止执行
set_exception_handler('ExceptionHandler');
 
throw new Exception('Uncaught Exception occurred');
?>

admin PHP

  1. 本文目前尚无任何评论.
  1. 本文目前尚无任何 trackbacks 和 pingbacks.