![]() |
|
首页 │ Apache │ Linux│ Java│ MySQL│ 注册│帮助 | |||
刚看了一个贴说php5不能捕捉不可知异常
这里我用exception & set_error_handler 来实现,但有部分工作起来不完善,请大家指正
[php]
<?
class MyException extends Exception{
protected $userErrMsg = "";
protected $userErrCode = -1;
protected $fatal = false;
/* userErrCode definition
0 -- Fatal error, program needs to stop
*/
function __construct($userErrInfo="", $userErrNum=-1, $sysErrInfo="", $sysErrNum=-1)
{
$this->userErrMsg = $userErrInfo; //set user defined error number and message
$this->userErrCode = $userErrNum;
if($this->userErrCode == ERR_FATAL)
$this->fatal = true;
parent::__construct($sysErrInfo, $sysErrNum); //set system error code and message
}
//Output user defined error message
public function getUserMessage()
{
if ($this->userErrMsg !== "")
return $this->userErrMsg;
else return "User Error Message Not Found";
}
//Output user defined error code
public function getUserCode()
{
if ($this->userErrCode !== -1) return $this->userErrCode;
else return "User Error Code Not Found";
}
public function fatal()
{
return $this->fatal;
}
}// end of MyException class
define("ERR_FATAL", 0);
define("ERR_WARNING", 1);
define("ERR_NOTICE", 2);
error_reporting(E_STRICT); //report all error
function myErrorHandler($errno, $errstr, $errfile, $errline)
{
switch ($errno){
case E_ERROR: //fatal runtime error
$errMsg = "Error#[$errno]: $errstr \n";
$errMsg.= "Fatal error in line $errline of file $errfile\n";
$errMsg.= "PHP " . PHP_VERSION . " (" . PHP_OS . ")\n";
$errMsg.= "Aborting...\n";
throw new MyException($errMsg, ERR_FATAL);
break;
case E_NOTICE:
$errMsg = "NOTICE: [$errno] $errstr\n";
$errMsg.= "Error in line $errline of file $errfile\n";
throw new MyException(nl2br($errMsg), ERR_NOTICE);
break;
break;
case E_WARNING:
$errMsg = "WARNING: [$errno] $errstr\n";
$errMsg.= "Error in line $errline of file $errfile\n";
throw new MyException(nl2br($errMsg), ERR_WARNING);
break;
default:
throw new MyException("Unkown error type: [$errno] $errstr
\n", ERR_NOTICE);
break;
}
}
// set to the user defined error handler
set_error_handler("myErrorHandler");
try{
echo "message before error
"; //will print
//以下是两个错误,一个是除零,另外是没定义
//因为每个错误都会触发catch,所以一次只能测一个,其他的用 //注释掉
// $a = 6/0; //trigger a division error
echo $abc; //trigger an undefine variable error
// $returnValue = undefinedFunction(); //此错误捕捉不到,高手请解释
echo "message after error"; //wont print because the error above has been catched
}
catch(MyException $e){
echo $e->getUserMessage();
}
?>
[/php]

