search
HomeBackend DevelopmentPHP TutorialA PHP error and exception handling class with very good display effect_PHP Tutorial

一、效果图:

A PHP error and exception handling class with very good display effect_PHP Tutorial

2. Implementation code

Copy code The code is as follows:

// 自定义异常函数
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 = '' . $message . '
PHP:' . $logTrace;
   self::writeErrorLog($messageSave);
  }

  if ($show) {
   self::showError('system', "

  • $message
  • ", $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 .= '

  • [Line: ' . $error['line'] . ']' . $file . '(' . $func . ')
  • ';
       $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 .= '

    ';
        $errorMsg .= self::sqlClear($exception->getSql(), $exception->getDbConfig());
        $errorMsg .= '
    ';
       }
      } 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 = 'User: userId=' . intval($userId) . '; IP=' . $ip . '; RIP:' . $_SERVER['REMOTE_ADDR'];
      $uri = 'Request: ' . htmlspecialchars(self::clear($_SERVER['REQUEST_URI']));
      $message = "\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] != '') {
           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


     $host - $title Error
     
     
     



    $title Error


    $errorMsg

    EOT;
      if (!empty($phpMsg)) {
       echo '
    ';
       echo '

    PHP Debug

    ';
       echo '';
       if (is_array($phpMsg)) {
        echo '';
        foreach ($phpMsg as $k => $msg) {
         $k++;
         echo '';
         echo '';
         echo '';
         echo '';
         echo '';
         echo '';
        }
       } else {
        echo '';
       }
       echo '
    No. File Line Code
    ' . $k . '' . $msg['file'] . '' . $msg['line'] . '' . $msg['function'] . '
      ' . $phpMsg . '
    ';
      }
      echo



    EOT;
      exit();
     }
    }

    /**
    * DB exception class
    *
    * @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;
     }
    }

    www.bkjia.comtruehttp://www.bkjia.com/PHPjc/744334.htmlTechArticle一、效果图: 二、实现代码 复制代码 代码如下: ?php // 自定义异常函数 set_exception_handler('handle_exception'); // 自定义错误函数 set_error_handler...
    Statement
    The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
    The Continued Use of PHP: Reasons for Its EnduranceThe Continued Use of PHP: Reasons for Its EnduranceApr 19, 2025 am 12:23 AM

    What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

    PHP and Python: Exploring Their Similarities and DifferencesPHP and Python: Exploring Their Similarities and DifferencesApr 19, 2025 am 12:21 AM

    PHP and Python are both high-level programming languages ​​that are widely used in web development, data processing and automation tasks. 1.PHP is often used to build dynamic websites and content management systems, while Python is often used to build web frameworks and data science. 2.PHP uses echo to output content, Python uses print. 3. Both support object-oriented programming, but the syntax and keywords are different. 4. PHP supports weak type conversion, while Python is more stringent. 5. PHP performance optimization includes using OPcache and asynchronous programming, while Python uses cProfile and asynchronous programming.

    PHP and Python: Different Paradigms ExplainedPHP and Python: Different Paradigms ExplainedApr 18, 2025 am 12:26 AM

    PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

    PHP and Python: A Deep Dive into Their HistoryPHP and Python: A Deep Dive into Their HistoryApr 18, 2025 am 12:25 AM

    PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

    Choosing Between PHP and Python: A GuideChoosing Between PHP and Python: A GuideApr 18, 2025 am 12:24 AM

    PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

    PHP and Frameworks: Modernizing the LanguagePHP and Frameworks: Modernizing the LanguageApr 18, 2025 am 12:14 AM

    PHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

    PHP's Impact: Web Development and BeyondPHP's Impact: Web Development and BeyondApr 18, 2025 am 12:10 AM

    PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

    How does PHP type hinting work, including scalar types, return types, union types, and nullable types?How does PHP type hinting work, including scalar types, return types, union types, and nullable types?Apr 17, 2025 am 12:25 AM

    PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values ​​and handle functions that may return null values.

    See all articles

    Hot AI Tools

    Undresser.AI Undress

    Undresser.AI Undress

    AI-powered app for creating realistic nude photos

    AI Clothes Remover

    AI Clothes Remover

    Online AI tool for removing clothes from photos.

    Undress AI Tool

    Undress AI Tool

    Undress images for free

    Clothoff.io

    Clothoff.io

    AI clothes remover

    Video Face Swap

    Video Face Swap

    Swap faces in any video effortlessly with our completely free AI face swap tool!

    Hot Tools

    Notepad++7.3.1

    Notepad++7.3.1

    Easy-to-use and free code editor

    Dreamweaver Mac version

    Dreamweaver Mac version

    Visual web development tools

    ZendStudio 13.5.1 Mac

    ZendStudio 13.5.1 Mac

    Powerful PHP integrated development environment

    SAP NetWeaver Server Adapter for Eclipse

    SAP NetWeaver Server Adapter for Eclipse

    Integrate Eclipse with SAP NetWeaver application server.

    DVWA

    DVWA

    Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software