search
HomeBackend DevelopmentPHP ProblemHow to write php interception exception

php interception exceptions can be written through PHP's error and exception mechanisms and its built-in numbers 'set_exception_handler', 'set_error_handler', and 'register_shutdown_function'.

How to write php interception exception

'set_exception_handler' function is used to intercept various uncaught exceptions and then hand them over to user-defined Method to handle

'set_error_handler' function can intercept various errors and then hand them over to the user-defined method for processing (recommended learning: PHP video tutorial)

'register_shutdown_function' function is a function called at the end of the PHP script. With 'error_get_last', you can get the last fatal error

This idea Generally speaking, errors, exceptions, and fatal errors are intercepted and handed over to our customized methods for processing. We identify whether these errors and exceptions are fatal. If so, record them in the database or file system, and then use scripts to continuously scan these errors. Log, if a serious error is found, immediately send an email or send a text message to alert

First we define an error interception class, which is used to intercept errors and exceptions and process them with our own defined processing methods. This class is placed in the file named 'errorHandler.class.php', and the code is as follows

/**
 * 文件名称:baseErrorHandler.class.php
 * 摘 要:错误拦截器父类
 */
require 'errorHandlerException.class.php';//异常类
class errorHandler
{
 public $argvs = array();
 public  $memoryReserveSize = 262144;//备用内存大小
 private $_memoryReserve;//备用内存
 /**
  * 方  法:注册自定义错误、异常拦截器
  * 参  数:void
  * 返  回:void
  */
 public function register()
 {
  ini_set('display_errors', 0);
  set_exception_handler(array($this, 'handleException'));//截获未捕获的异常
  set_error_handler(array($this, 'handleError'));//截获各种错误 此处切不可掉换位置
  //留下备用内存 供后面拦截致命错误使用
  $this->memoryReserveSize > 0 && $this->_memoryReserve = str_repeat('x', $this->memoryReserveSize);
  register_shutdown_function(array($this, 'handleFatalError'));//截获致命性错误
 }
 /**
  * 方  法:取消自定义错误、异常拦截器
  * 参  数:void
  * 返  回:void
  */
 public function unregister()
 {
  restore_error_handler();
  restore_exception_handler();
 }
 /**
  * 方  法:处理截获的未捕获的异常
  * 参  数:Exception $exception
  * 返  回:void
  */
 public function handleException($exception)
 {
  $this->unregister();
  try
  {
   $this->logException($exception);
   exit(1);
  }
  catch(Exception $e)
  {
   exit(1);
  }
 }
 /**
  * 方  法:处理截获的错误
  * 参  数:int  $code 错误代码
  * 参  数:string $message 错误信息
  * 参  数:string $file 错误文件
  * 参  数:int  $line 错误的行数
  * 返  回:boolean
  */
 public function handleError($code, $message, $file, $line)
 {
  //该处思想是将错误变成异常抛出 统一交给异常处理函数进行处理
  if((error_reporting() & $code) && !in_array($code, array(E_NOTICE, E_WARNING, E_USER_NOTICE, E_USER_WARNING, E_DEPRECATED)))
  {//此处只记录严重的错误 对于各种WARNING NOTICE不作处理
   $exception = new errorHandlerException($message, $code, $code, $file, $line);
   $trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
   array_shift($trace);//trace的第一个元素为当前对象 移除
   foreach($trace as $frame) 
   {
    if($frame['function'] == '__toString') 
    {//如果错误出现在 __toString 方法中 不抛出任何异常
     $this->handleException($exception);
     exit(1);
    }
   }
   throw $exception;
  }
  return false;
 }
 /**
  * 方  法:截获致命性错误
  * 参  数:void
  * 返  回:void
  */
 public function handleFatalError()
 {
  unset($this->_memoryReserve);//释放内存供下面处理程序使用
  $error = error_get_last();//最后一条错误信息
  if(errorHandlerException::isFatalError($error))
  {//如果是致命错误进行处理
   $exception = new errorHandlerException($error['message'], $error['type'], $error['type'], $error['file'], $error['line']);
   $this->logException($exception);
   exit(1);
  }
 }
 /**
  * 方  法:获取服务器IP
  * 参  数:void
  * 返  回:string
  */
 final public function getServerIp()
 {
  $serverIp = '';
  if(isset($_SERVER['SERVER_ADDR']))
  {
   $serverIp = $_SERVER['SERVER_ADDR'];
  }
  elseif(isset($_SERVER['LOCAL_ADDR']))
  {
   $serverIp = $_SERVER['LOCAL_ADDR'];
  }
  elseif(isset($_SERVER['HOSTNAME']))
  {
   $serverIp = gethostbyname($_SERVER['HOSTNAME']);
  }
  else
  {
   $serverIp = getenv('SERVER_ADDR');
  }  
  return $serverIp; 
 }
 /**
  * 方  法:获取当前URI信息
  * 参  数:void
  * 返  回:string $url
  */
 public function getCurrentUri()
 {
  $uri = '';
  if($_SERVER ["REMOTE_ADDR"])
  {//浏览器浏览模式
   $uri = 'http://' . $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI'];
  }
  else
  {//命令行模式
   $params = $this->argvs;
   $uri = $params[0];
   array_shift($params);
   for($i = 0, $len = count($params); $i < $len; $i++)
   {
    $uri .= &#39; &#39; . $params[$i];
   }
  }
  return $uri;
 }
 /**
  * 方  法:记录异常信息
  * 参  数:errorHandlerException $e 错误异常
  * 返  回:boolean 是否保存成功
  */
 final public function logException($e)
 {
  $error = array(
      &#39;add_time&#39;  =>  time(),
      &#39;title&#39;  =>  errorHandlerException::getName($e->getCode()),//这里获取用户友好型名称
      &#39;message&#39;  =>  array(),
      &#39;server_ip&#39; =>  $this->getServerIp(),
      &#39;code&#39;   =>  errorHandlerException::getLocalCode($e->getCode()),//这里为各种错误定义一个编号以便查找
      &#39;file&#39;   => $e->getFile(),
      &#39;line&#39;   =>  $e->getLine(),
      &#39;url&#39;  => $this->getCurrentUri(),
     );
  do
  {
   //$e->getFile() . &#39;:&#39; . $e->getLine() . &#39; &#39; . $e->getMessage() . &#39;(&#39; . $e->getCode() . &#39;)&#39;
   $message = (string)$e;
   $error[&#39;message&#39;][] = $message;
  } while($e = $e->getPrevious());
  $error[&#39;message&#39;] = implode("\r\n", $error[&#39;message&#39;]);
  $this->logError($error);
 }
 /**
  * 方  法:记录异常信息
  * 参  数:array $error = array(
  *         &#39;time&#39; => int, 
  *         &#39;title&#39; => &#39;string&#39;, 
  *         &#39;message&#39; => &#39;string&#39;, 
  *         &#39;code&#39; => int,
  *         &#39;server_ip&#39; => &#39;string&#39;
  *          &#39;file&#39;  => &#39;string&#39;,
  *         &#39;line&#39; => int,
  *         &#39;url&#39; => &#39;string&#39;,
  *        );
  * 返  回:boolean 是否保存成功
  */
 public function logError($error)
 {
  /*这里去实现如何将错误信息记录到日志*/
 }
}

In the above code, there is an 'errorHandlerException' class, which is placed in the file 'errorHandlerException.class.php', This class is used to convert errors into exceptions in order to record the file, line number, error code, error message and other information where the error occurred. At the same time, its method 'isFatalError' is used to identify whether the error is a fatal error.

The above is the detailed content of How to write php interception exception. For more information, please follow other related articles on the PHP Chinese website!

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
ACID vs BASE Database: Differences and when to use each.ACID vs BASE Database: Differences and when to use each.Mar 26, 2025 pm 04:19 PM

The article compares ACID and BASE database models, detailing their characteristics and appropriate use cases. ACID prioritizes data integrity and consistency, suitable for financial and e-commerce applications, while BASE focuses on availability and

PHP Secure File Uploads: Preventing file-related vulnerabilities.PHP Secure File Uploads: Preventing file-related vulnerabilities.Mar 26, 2025 pm 04:18 PM

The article discusses securing PHP file uploads to prevent vulnerabilities like code injection. It focuses on file type validation, secure storage, and error handling to enhance application security.

PHP Input Validation: Best practices.PHP Input Validation: Best practices.Mar 26, 2025 pm 04:17 PM

Article discusses best practices for PHP input validation to enhance security, focusing on techniques like using built-in functions, whitelist approach, and server-side validation.

PHP API Rate Limiting: Implementation strategies.PHP API Rate Limiting: Implementation strategies.Mar 26, 2025 pm 04:16 PM

The article discusses strategies for implementing API rate limiting in PHP, including algorithms like Token Bucket and Leaky Bucket, and using libraries like symfony/rate-limiter. It also covers monitoring, dynamically adjusting rate limits, and hand

PHP Password Hashing: password_hash and password_verify.PHP Password Hashing: password_hash and password_verify.Mar 26, 2025 pm 04:15 PM

The article discusses the benefits of using password_hash and password_verify in PHP for securing passwords. The main argument is that these functions enhance password protection through automatic salt generation, strong hashing algorithms, and secur

OWASP Top 10 PHP: Describe and mitigate common vulnerabilities.OWASP Top 10 PHP: Describe and mitigate common vulnerabilities.Mar 26, 2025 pm 04:13 PM

The article discusses OWASP Top 10 vulnerabilities in PHP and mitigation strategies. Key issues include injection, broken authentication, and XSS, with recommended tools for monitoring and securing PHP applications.

PHP XSS Prevention: How to protect against XSS.PHP XSS Prevention: How to protect against XSS.Mar 26, 2025 pm 04:12 PM

The article discusses strategies to prevent XSS attacks in PHP, focusing on input sanitization, output encoding, and using security-enhancing libraries and frameworks.

PHP Interface vs Abstract Class: When to use each.PHP Interface vs Abstract Class: When to use each.Mar 26, 2025 pm 04:11 PM

The article discusses the use of interfaces and abstract classes in PHP, focusing on when to use each. Interfaces define a contract without implementation, suitable for unrelated classes and multiple inheritance. Abstract classes provide common funct

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.