欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

一个显示效果非常不错的PHP错误、异常处理类

程序员文章站 2022-06-03 17:23:23
一、效果图: 二、实现代码 复制代码 代码如下:

一、效果图:

一个显示效果非常不错的PHP错误、异常处理类

二、实现代码

复制代码 代码如下:
<?php

// 自定义异常函数
set_exception_handler('handle_exception');

// 自定义错误函数
set_error_handler('handle_error');

/**
 * 异常处理
 *
 * @param mixed $exception 异常对象
 * @author blog.snsgou.com
 */
function handle_exception($exception) {
 error::exceptionerror($exception);
}

/**
 * 错误处理
 *
 * @param string $errno 错误代码
 * @param string $errstr 错误信息
 * @param string $errfile 出错文件
 * @param string $errline 出错行
 * @author blog.snsgou.com
 */
function handle_error($errno, $errstr, $errfile, $errline) {
 if ($errno) {
  error::systemerror($errstr, false, true, false);
 }
}

/**
 * 系统错误处理
 *
 * @author blog.snsgou.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 blog.snsgou.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;
 }
}