Home Backend Development PHP Problem How to write php interception exception

How to write php interception exception

Nov 12, 2019 pm 02:08 PM
php

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!

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

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

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian Dec 24, 2024 pm 04:42 PM

PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

How To Set Up Visual Studio Code (VS Code) for PHP Development How To Set Up Visual Studio Code (VS Code) for PHP Development Dec 20, 2024 am 11:31 AM

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

7 PHP Functions I Regret I Didn't Know Before 7 PHP Functions I Regret I Didn't Know Before Nov 13, 2024 am 09:42 AM

If you are an experienced PHP developer, you might have the feeling that you’ve been there and done that already.You have developed a significant number of applications, debugged millions of lines of code, and tweaked a bunch of scripts to achieve op

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

How do you parse and process HTML/XML in PHP? How do you parse and process HTML/XML in PHP? Feb 07, 2025 am 11:57 AM

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

PHP Program to Count Vowels in a String PHP Program to Count Vowels in a String Feb 07, 2025 pm 12:12 PM

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? Apr 03, 2025 am 12:03 AM

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.

See all articles