How to write php interception exception

(*-*)浩
Release: 2023-02-28 13:54:02
Original
2886 people have browsed it

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)
 {
  /*这里去实现如何将错误信息记录到日志*/
 }
}
Copy after login

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!

Related labels:
php
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!