$test.php
<?php
function exceptionhandler_1($e)
{
echo '自定义的异常处理器1<br/>函数名称:' . __FUNCTION__ . "<br/>";
echo "异常信息:" . $e->getMessage();
}
function exceptionHandler_2($e)
{
echo "自定义异常处理器2<br/>函数名称:" . __FUNCTION__ . "<br/>";
echo "异常信息:" . $e->getMessage();
}
set_exception_handler('exceptionhandler_1');
set_exception_handler('exceptionhandler_2');
//恢复到上一次定义过的异常处理函数(异常处理器1)
restore_exception_handler();
//restore_exception_handler();
throw new Exception('测试自定义异常处理器');
echo "this is a test";//不执行
?>
ExceptionHandler.php
<?php
class ExceptionHandler
{
protected $_exception;
protected $_logFile = "D:/error/testExceptionHandler.log";
public function __construct(Exception $e)
{
$this->_exception = $e;
}
public static function handle(Exception $e)
{
$self = new self($e);
$self->log();
echo $self;
}
public function log()
{
error_log($this->_exception->getMessage() . PHP_EOL, 3, $this->_logFile);
}
public function __toString()
{
$message = <<<EOF
<html>
<head><title></title></head>
<body><h1>太不可思议啦,出现异常了</h1>
<p><a href="mailto:403133112@qq.com">联系管理员</a> </p></body>
</html>
EOF;
return $message;
}
}
set_exception_handler(array('ExceptionHandler', 'handle'));
try {
throw new Exception('this is a test');
} catch (Exception $e) {
echo $e->getMessage();
}
echo "<hr/>";
throw new Exception("测试自定义的异常处理器hello world");
?>