笔记:自定义异常处理器
/**
* 自定义异常类处理器
* Class ExceptionHandler
*/
class ExceptionHandler
{
protected $_exception;
protected $_logFile = __DIR__.'/exception_handle.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);
}
/**
* 魔术方法__toString()
* 快速获取对象的字符串信息的便捷方式,直接输出对象引用时自动调用的方法。
* @return string
*/
public function __toString()
{
$message = <<<EOF
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>出现异常了啊啊啊啊</h1>
</body>
</html>
EOF;
return $message;
}
}
set_exception_handler(array('ExceptionHandler','handle'));
/**
* try catch不会被自定义异常处理!!!!
*/
try{
throw new Exception('this is a test');
}catch (Exception $exception) {
echo $exception->getMessage();
}
throw new Exception('测试自定义的异常处理器');
/**
* 自定义异常函数处理器
*/
header('content-type:text/html;charset=utf-8');
function exceptionHandler_1($e)
{
echo '自定义异常处理器1<br/>函数名:'.__FUNCTION__.PHP_EOL;
echo '异常信息:'.$e->getMessage();
}
function exceptionHandler_2($e)
{
echo '自定义异常处理器2<br/>函数名:'.__FUNCTION__.PHP_EOL;
echo '异常信息:'.$e->getMessage();
}
set_exception_handler('exceptionHandler_1');
//set_exception_handler('exceptionHandler_2');
//恢复到上一次定义过的异常处理函数,即exceptionHandler_1
//restore_exception_handler();
//致命错误信息
//restore_exception_handler();
throw new Exception('测试自定义异常处理器');
//自定义异常处理器,不会向下继续执行;异常被捕获之后,会继续执行
//回顾:自定义错误处理器会继续执行代码,而手动抛出的错误信息不会继续执行
echo 'test';