版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_20025577/article/details/85059762
<?php
class App
{
public function __construct()
{
/*
* ini_set 设置配置项
* display_errors 是否在页面显示错误信息
*/
ini_set('display_errors', 0);
$this->setSysHandler();
}
public function setSysHandler()
{
//php中止时执行
register_shutdown_function([$this, 'fatalHandler']);
//设置用户自定义的错误处理函数
set_error_handler([$this, 'errorHandler']);
//设置用户自定义的异常处理函数
set_exception_handler([$this, 'exceptionHandler']);
}
// 错误被包装成为异常抛出
public function errorHandler($code, $msg, $file, $line)
{
throw new ErrorException($msg, $code, $code, $file, $line);
}
public function fatalHandler()
{
if ($errors = error_get_last()) {
$msg = $errors['message'];
$code = $errors['type'];
$file = $errors['file'];
$line = $errors['line'];
echo "<font size='7'>:(</font><h2> 文件: {$file}; 行号: {$line};</h2>";
echo "<h4>错误信息: {$msg}; 错误代码: {$code}</h4>";
echo "<pre>";
}
}
public function exceptionHandler($excep)
{
$this->handler($excep);
}
public function handler($excep)
{
$msg = $excep->getMessage();//获取异常消息内容
$code = $excep->getCode();//获取异常代码
$file = $excep->getFile();//创建异常时的程序文件名称
$line = $excep->getLine();//获取创建的异常所在文件中的行号
$trace = $excep->getTrace();//获取异常追踪信息
$this->errorlog($msg, $code, $file, $line);//发送错误信息到某个地方
echo "<font size='7'>:(</font><h2> 文件: {$file}; 行号: {$line};</h2>";
echo "<h4>错误信息: {$msg}; 错误代码: {$code}</h4>";
echo "<pre>";
if ($excep instanceof ErrorException) {
array_shift($trace);
}
print_r($trace);
//函数的调用栈
}
public function errorlog($msg, $code, $file, $line)
{
$str = date('Y-m-d H:i:s') . "\r\n";
$str .= "错误信息是:";
$str .= $msg;
$str .= "\r\n";
$str .= "错误行号是:";
$str .= $line;
$str .= "\r\n";
$str .= "错误代码是:";
$str .= $code;
$str .= "\r\n";
$str .= "错误行文件:";
$str .= $file;
$str .= "\r\n";
$str .= "\r\n";
error_log($str, 3, './myerror.log');
}
}
$app = new App();