<?php

// 自定义异常函数
set_exception_handler('handle_exception'); // 自定义错误函数
set_error_handler('handle_error'); /**
* 异常处理
*
* @param mixed $exception 异常对象
* @author 52php.cnblogs.com
*/
function handle_exception($exception) {
Error::exceptionError($exception);
} /**
* 错误处理
*
* @param string $errNo 错误代码
* @param string $errStr 错误信息
* @param string $errFile 出错文件
* @param string $errLine 出错行
* @author 52php.cnblogs.com
*/
function handle_error($errNo, $errStr, $errFile, $errLine) {
if ($errNo) {
Error::systemError($errStr, false, true, false);
}
} /**
* 系统错误处理
*
* @author 52php.cnblogs.com
*/
class Error { public static function systemError($message, $show = true, $save = true, $halt = true) { list($showTrace, $logTrace) = self::debugBacktrace(); if ($save) {
$messageSave = '<b>' . $message . '</b><br /><b>PHP:</b>' . $logTrace;
self::writeErrorLog($messageSave);
} if ($show) {
self::showError('system', "<li>$message</li>", $showTrace, 0);
} if ($halt) {
exit();
} else {
return $message;
}
} /**
* 代码执行过程回溯信息
*
* @static
* @access public
*/
public static function debugBacktrace() {
$skipFunc[] = 'Error->debugBacktrace'; $show = $log = '';
$debugBacktrace = debug_backtrace();
ksort($debugBacktrace);
foreach ($debugBacktrace as $k => $error) {
if (!isset($error['file'])) {
// 利用反射API来获取方法/函数所在的文件和行数
try {
if (isset($error['class'])) {
$reflection = new ReflectionMethod($error['class'], $error['function']);
} else {
$reflection = new ReflectionFunction($error['function']);
}
$error['file'] = $reflection->getFileName();
$error['line'] = $reflection->getStartLine();
} catch (Exception $e) {
continue;
}
} $file = str_replace(SITE_PATH, '', $error['file']);
$func = isset($error['class']) ? $error['class'] : '';
$func .= isset($error['type']) ? $error['type'] : '';
$func .= isset($error['function']) ? $error['function'] : '';
if (in_array($func, $skipFunc)) {
break;
}
$error['line'] = sprintf('%04d', $error['line']); $show .= '<li>[Line: ' . $error['line'] . ']' . $file . '(' . $func . ')</li>';
$log .= !empty($log) ? ' -> ' : '';
$log .= $file . ':' . $error['line'];
}
return array($show, $log);
} /**
* 异常处理
*
* @static
* @access public
* @param mixed $exception
*/
public static function exceptionError($exception) {
if ($exception instanceof DbException) {
$type = 'db';
} else {
$type = 'system';
}
if ($type == 'db') {
$errorMsg = '(' . $exception->getCode() . ') ';
$errorMsg .= self::sqlClear($exception->getMessage(), $exception->getDbConfig());
if ($exception->getSql()) {
$errorMsg .= '<div class="sql">';
$errorMsg .= self::sqlClear($exception->getSql(), $exception->getDbConfig());
$errorMsg .= '</div>';
}
} else {
$errorMsg = $exception->getMessage();
}
$trace = $exception->getTrace();
krsort($trace);
$trace[] = array('file' => $exception->getFile(), 'line' => $exception->getLine(), 'function' => 'break');
$phpMsg = array();
foreach ($trace as $error) {
if (!empty($error['function'])) {
$fun = '';
if (!empty($error['class'])) {
$fun .= $error['class'] . $error['type'];
}
$fun .= $error['function'] . '(';
if (!empty($error['args'])) {
$mark = '';
foreach ($error['args'] as $arg) {
$fun .= $mark;
if (is_array($arg)) {
$fun .= 'Array';
} elseif (is_bool($arg)) {
$fun .= $arg ? 'true' : 'false';
} elseif (is_int($arg)) {
$fun .= (defined('SITE_DEBUG') && SITE_DEBUG) ? $arg : '%d';
} elseif (is_float($arg)) {
$fun .= (defined('SITE_DEBUG') && SITE_DEBUG) ? $arg : '%f';
} else {
$fun .= (defined('SITE_DEBUG') && SITE_DEBUG) ? '\'' . htmlspecialchars(substr(self::clear($arg), 0, 10)) . (strlen($arg) > 10 ? ' ...' : '') . '\'' : '%s';
}
$mark = ', ';
}
}
$fun .= ')';
$error['function'] = $fun;
}
if (!isset($error['line'])) {
continue;
}
$phpMsg[] = array('file' => str_replace(array(SITE_PATH, '\\'), array('', '/'), $error['file']), 'line' => $error['line'], 'function' => $error['function']);
}
self::showError($type, $errorMsg, $phpMsg);
exit();
} /**
* 记录错误日志
*
* @static
* @access public
* @param string $message
*/
public static function writeErrorLog($message) { return false; // 暂时不写入 $message = self::clear($message);
$time = time();
$file = LOG_PATH . '/' . date('Y.m.d') . '_errorlog.php';
$hash = md5($message); $userId = 0;
$ip = get_client_ip(); $user = '<b>User:</b> userId=' . intval($userId) . '; IP=' . $ip . '; RIP:' . $_SERVER['REMOTE_ADDR'];
$uri = 'Request: ' . htmlspecialchars(self::clear($_SERVER['REQUEST_URI']));
$message = "<?php exit;?>\t{$time}\t$message\t$hash\t$user $uri\n"; // 判断该$message是否在时间间隔$maxtime内已记录过,有,则不用再记录了
if (is_file($file)) {
$fp = @fopen($file, 'rb');
$lastlen = 50000; // 读取最后的 $lastlen 长度字节内容
$maxtime = 60 * 10; // 时间间隔:10分钟
$offset = filesize($file) - $lastlen;
if ($offset > 0) {
fseek($fp, $offset);
}
if ($data = fread($fp, $lastlen)) {
$array = explode("\n", $data);
if (is_array($array))
foreach ($array as $key => $val) {
$row = explode("\t", $val);
if ($row[0] != '<?php exit;?>') {
continue;
}
if ($row[3] == $hash && ($row[1] > $time - $maxtime)) {
return;
}
}
}
} error_log($message, 3, $file);
} /**
* 清除文本部分字符
*
* @param string $message
*/
public static function clear($message) {
return str_replace(array("\t", "\r", "\n"), " ", $message);
} /**
* sql语句字符清理
*
* @static
* @access public
* @param string $message
* @param string $dbConfig
*/
public static function sqlClear($message, $dbConfig) {
$message = self::clear($message);
if (!(defined('SITE_DEBUG') && SITE_DEBUG)) {
$message = str_replace($dbConfig['database'], '***', $message);
//$message = str_replace($dbConfig['prefix'], '***', $message);
$message = str_replace(C('DB_PREFIX'), '***', $message);
}
$message = htmlspecialchars($message);
return $message;
} /**
* 显示错误
*
* @static
* @access public
* @param string $type 错误类型 db,system
* @param string $errorMsg
* @param string $phpMsg
*/
public static function showError($type, $errorMsg, $phpMsg = '') {
global $_G; $errorMsg = str_replace(SITE_PATH, '', $errorMsg);
ob_end_clean();
$host = $_SERVER['HTTP_HOST'];
$title = $type == 'db' ? 'Database' : 'System';
echo <<<EOT
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<title>$host - $title Error</title>
<meta http-equiv="Content-Type" content="text/html; charset={$_G['config']['output']['charset']}" />
<meta name="ROBOTS" content="NOINDEX,NOFOLLOW,NOARCHIVE" />
<style type="text/css">
<!--
body { background-color: white; color: black; font: 9pt/11pt verdana, arial, sans-serif;}
#container {margin: 10px;}
#message {width: 1024px; color: black;}
.red {color: red;}
a:link {font: 9pt/11pt verdana, arial, sans-serif; color: red;}
a:visited {font: 9pt/11pt verdana, arial, sans-serif; color: #4e4e4e;}
h1 {color: #FF0000; font: 18pt "Verdana"; margin-bottom: 0.5em;}
.bg1 {background-color: #FFFFCC;}
.bg2 {background-color: #EEEEEE;}
.table {background: #AAAAAA; font: 11pt Menlo,Consolas,"Lucida Console"}
.info {
background: none repeat scroll 0 0 #F3F3F3;
border: 0px solid #aaaaaa;
border-radius: 10px 10px 10px 10px;
color: #000000;
font-size: 11pt;
line-height: 160%;
margin-bottom: 1em;
padding: 1em;
} .help {
background: #F3F3F3;
border-radius: 10px 10px 10px 10px;
font: 12px verdana, arial, sans-serif;
text-align: center;
line-height: 160%;
padding: 1em;
} .sql {
background: none repeat scroll 0 0 #FFFFCC;
border: 1px solid #aaaaaa;
color: #000000;
font: arial, sans-serif;
font-size: 9pt;
line-height: 160%;
margin-top: 1em;
padding: 4px;
}
-->
</style>
</head>
<body>
<div id="container">
<h1>$title Error</h1>
<div class='info'>$errorMsg</div>
EOT;
if (!empty($phpMsg)) {
echo '<div class="info">';
echo '<p><strong>PHP Debug</strong></p>';
echo '<table cellpadding="5" cellspacing="1" width="100%" class="table"><tbody>';
if (is_array($phpMsg)) {
echo '<tr class="bg2"><td>No.</td><td>File</td><td>Line</td><td>Code</td></tr>';
foreach ($phpMsg as $k => $msg) {
$k++;
echo '<tr class="bg1">';
echo '<td>' . $k . '</td>';
echo '<td>' . $msg['file'] . '</td>';
echo '<td>' . $msg['line'] . '</td>';
echo '<td>' . $msg['function'] . '</td>';
echo '</tr>';
}
} else {
echo '<tr><td><ul>' . $phpMsg . '</ul></td></tr>';
}
echo '</tbody></table></div>';
}
echo <<<EOT
</div>
</body>
</html>
EOT;
exit();
}
} /**
* DB异常类
*
* @author 52php.cnblogs.com
*/
class DbException extends Exception { protected $sql;
protected $dbConfig; // 当前数据库配置信息 public function __construct($message, $code = 0, $sql = '', $dbConfig = array()) {
$this->sql = $sql;
$this->dbConfig = $dbConfig;
parent::__construct($message, $code);
} public function getSql() {
return $this->sql;
} public function getDbConfig() {
return $this->dbConfig;
}
}

效果图:

自定义PHP系统异常处理类的更多相关文章

  1. Spring MVC自定义统一异常处理类,并且在控制台中输出错误日志

    在使用SimpleMappingExceptionResolver实现统一异常处理后(参考Spring MVC的异常统一处理方法), 发现出现异常时,log4j无法在控制台输出错误日志.因此需要自定义 ...

  2. JS面向对象(1) -- 简介,入门,系统常用类,自定义类,constructor,typeof,instanceof,对象在内存中的表现形式

    相关链接: JS面向对象(1) -- 简介,入门,系统常用类,自定义类,constructor,typeof,instanceof,对象在内存中的表现形式 JS面向对象(2) -- this的使用,对 ...

  3. springmvc自定义异常处理类和<mvc:annotation-driven/>自带异常处理优先级问题

    自定义异常类的优先级低于注解驱动的默认异常处理,所以可以给自定义异常处理类,实现一个排序的接口, org.springframework.core.Ordered 改接口的注释: /**  * {@c ...

  4. php 异常处理类

    PHP具有很多异常处理类,其中Exception是所有异常处理的基类. Exception具有几个基本属性与方法,其中包括了: message 异常消息内容code 异常代码file 抛出异常的文件名 ...

  5. 扩展PHP内置的异常处理类

    在try代码块中,需要使用throw语句抛出一个异常对象,才能跳到转到catch代码块中执行,并在catch代码块中捕获并使用这个异常类的对象.虽然在PHP中提供的内置异常处理类Exception,已 ...

  6. 自定义VS程序异常处理及调试Dump文件(一)

    自定义VS程序异常处理及调试Dump文件(一) 1. Dump文件 1. Dump文件介绍 Dump文件(Dump File),也叫转储文件,以.DMP为文件后缀.dump文件是进程在内存中的镜像文件 ...

  7. thinkphp 5.0如何实现自定义404(异常处理)页面

    404页面是客户端在浏览网页时,由于服务器无法正常提供信息,或是服务器无法回应,且不知道原因所返回的页面.404承载着用户体验与SEO优化的重任.404页面通常为用户访问了网站上不存在或已删除的页面, ...

  8. ASP.NET Core 2.2 : 二十一. 内容协商与自定义IActionResult和格式化类

    上一章的结尾留下了一个问题:同样是ObjectResult,在执行的时候又是如何被转换成string和JSON两种格式的呢? 本章来解答这个问题,这里涉及到一个名词:“内容协商”.除了这个,本章将通过 ...

  9. DRF内置认证组件之自定义认证系统

    自定义token认证 我们知道,在django项目中不管路由以及对应的视图类是如何写的,都会走到 dispatch 方法,进行路由分发, 在阅读 APIView类中的dispatch 方法的源码中,有 ...

随机推荐

  1. java设计模式之组合模式

    组合模式 组合模式,将对象组合成树形结构以表示“部分-整体”的层次结构,组合模式使得用户对单个对象和组合对象的使用具有一致性.掌握组合模式的重点是要理解清楚 “部分/整体” 还有 ”单个对象“ 与 & ...

  2. HDU1890 Robotic Sort[splay 序列]

    Robotic Sort Time Limit: 6000/2000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)Tota ...

  3. BZOJ1497: [NOI2006]最大获利[最小割 最大闭合子图]

    1497: [NOI2006]最大获利 Time Limit: 5 Sec  Memory Limit: 64 MBSubmit: 4375  Solved: 2142[Submit][Status] ...

  4. COGS182 [USACO Jan07] 均衡队形[RMQ]

    182. [USACO Jan07] 均衡队形 ★★   输入文件:lineup.in   输出文件:lineup.out   简单对比时间限制:4 s   内存限制:128 MB 题目描述 农夫约翰 ...

  5. PAT 1041. 考试座位号(15)

    每个PAT考生在参加考试时都会被分配两个座位号,一个是试机座位,一个是考试座位.正常情况下,考生在入场时先得到试机座位号码,入座进入试机状态后,系统会显示该考生的考试座位号码,考试时考生需要换到考试座 ...

  6. Spring.net使用说明

    使用方法: 1.在配置文件设置Spring.net 节点  在配置节中,声明Spring.net,配置 context,objects 标签,来源(type) <!--配置节:主要用来 配置 a ...

  7. 【C#】【Thread】SpinWait

    System.Threading.SpinWait 是一个轻量同步类型,可以在低级别方案中使用它来避免内核事件所需的高开销的上下文切换和内核转换. 在多核计算机上,当预计资源不会保留很长一段时间时,如 ...

  8. 微信小程序购物商城系统开发系列-目录结构

    上一篇我们简单介绍了一下微信小程序的IDE(微信小程序购物商城系统开发系列-工具篇),相信大家都已经蠢蠢欲试建立一个自己的小程序,去完成一个独立的商城网站. 先别着急我们一步步来,先尝试下写一个自己的 ...

  9. maven 项目启动tomcat报错 java.lang.ClassNotFoundException: org.springframework.web.context.ContextLoaderListener

    maven项目启动tomcat报错: java.lang.ClassNotFoundException: org.springframework.web.context.ContextLoaderLi ...

  10. ASP.NET MVC - 探究应用程序文件夹

    为了学习 ASP.NET MVC,我们将构建一个 Internet 应用程序. 第 2 部分:探究应用程序文件夹. MVC 文件夹 一个典型的 ASP.NET MVC Web 应用程序的文件夹内容如下 ...