Home Backend Development PHP Tutorial Customization of PHP exception handler

Customization of PHP exception handler

Dec 23, 2017 pm 03:18 PM
php processor abnormal

It is inevitable to encounter some abnormal errors in programming. What we have to do is to handle exceptions reasonably so that they are not perceived by users. Today I will share a method of customizing exception handlers.

Create a custom error handler

Creating a custom error handler is very simple. We simply created a dedicated function that can be called when an error occurs in PHP.

The function must be able to handle at least two parameters (error level and error message), but can accept up to five parameters (optional: file, line-number and error context):

Syntax

error_function(error_level,error_message,

error_file,error_line,error_context)

Parameter description

error_level

Required. Specifies the error reporting level for user-defined errors. Must be a value.

See the table below: Error reporting levels.

error_message Required. Specifies error messages for user-defined errors.

error_file Optional. Specifies the name of the file in which the error occurred.

error_line Optional. Specifies the line number where the error occurred.

error_context Optional. Specifies an array containing each variable in use when the error occurred and their values.

Error reporting levels

These error reporting levels are different types of errors that the error handler is designed to handle:

Value constant description

2 E_WARNING Nonfatal run-time error. Do not pause script execution.

8 E_NOTICE

Run-time notification.

The script detects that an error may occur, but it may also occur when the script is running normally.

256 E_USER_ERROR Fatal user-generated error. This is similar to E_ERROR set by the programmer using the PHP function trigger_error().

512 E_USER_WARNING Non-fatal user-generated warning. This is similar to the E_WARNING set by the programmer using the PHP function trigger_error().

1024 E_USER_NOTICE User generated notification. This is similar to E_NOTICE set by the programmer using the PHP function trigger_error().

4096 E_RECOVERABLE_ERROR Trapable fatal error. Like E_ERROR, but can be caught by a user-defined handler. (See set_error_handler())

8191 E_ALL

All errors and warnings except level E_STRICT.

(In PHP 6.0, E_STRICT is part of E_ALL)

Now, let us create a function that handles errors:

function customError($errno, $errstr)
{
echo "Error: [$errno] $errstr
";
echo "Ending Script";
die();
}
Copy after login

The above code is a simple error handling function. When it is triggered, it gets the error level and error message. It then prints the error level and message, and terminates the script.

Now that we have created an error handling function, we need to determine when to trigger the function.

Set Error Handler

PHP’s default error handler is the built-in error handler. We are going to transform the above function into the default error handler when the script is running.

The error handler can be modified so that it only applies to certain errors, so that the script can handle different errors in different ways. However, in this case, we are going to use our custom error handler for all errors:

set_error_handler("customError");

Since we want our custom function to To handle all errors, set_error_handler() requires only one parameter, and a second parameter can be added to specify the error level.

Example

Test this error handler by trying to output a variable that does not exist:

<?php
//error handler function
function customError($errno, $errstr)
{
echo "Error: [$errno] $errstr";
}
//set error handler
set_error_handler("customError");
//trigger error
echo($test);
?>
Copy after login

The output of the above code should look like this:

Error : [8] Undefined variable: test

Trigger error

In the script where the user inputs data, it is useful to trigger an error when the user's input is invalid. In PHP, this task is accomplished by trigger_error().

Example

In this example, if the "test" variable is greater than "1", an error will occur:

$ test=2;

if ($test>1)

{

trigger_error("Value must be 1 or below");

}

?>

The output of the above code should be similar to this:

Notice: Value must be 1 or below

in C:\webfolder\test. php on line 6

You can trigger an error anywhere in the script. By adding the second parameter, you can specify the error level that is triggered.

Possible error types:

E_USER_ERROR - Fatal user-generated run-time error. The error cannot be recovered. Script execution was interrupted.

E_USER_WARNING - Non-fatal user-generated run-time warning. Script execution is not interrupted.

E_USER_NOTICE - Default. User-generated run-time notifications. The script found a possible error, which may have occurred while the script was running normally.

Example

In this example, if the "test" variable is greater than "1", the E_USER_WARNING error occurs. If E_USER_WARNING occurs, we will use our custom error handler and end the script:

1)
{
trigger_error("Value must be 1 or below",E_USER_WARNING);
}
?>
Copy after login

The output of the above code should look like this:

Error: [512] Value must be 1 or below

Ending Script

Now that we have learned how to create our own errors, and how to trigger them, let's study error logging.

Error record

默认地,根据在 php.ini 中的 error_log 配置,PHP 向服务器的错误记录系统或文件发送错误记录。通过使用 error_log() 函数,您可以向指定的文件或远程目的地发送错误记录。

通过电子邮件向您自己发送错误消息,是一种获得指定错误的通知的好办法。

通过 E-Mail 发送错误消息

在下面的例子中,如果特定的错误发生,我们将发送带有错误消息的电子邮件,并结束脚本:

<?php
//error handler function
function customError($errno, $errstr)
{
echo "Error: [$errno] $errstr
";
echo "Webmaster has been notified";
error_log("Error: [$errno] $errstr",1,
"someone@example.com","From: webmaster@example.com");
}
//set error handler
set_error_handler("customError",E_USER_WARNING);
//trigger error
$test=2;
if ($test>1)
{
trigger_error("Value must be 1 or below",E_USER_WARNING);
}
?>
Copy after login

以上代码的输出应该类似这样:

Error: [512] Value must be 1 or below

Webmaster has been notified

接收自以上代码的邮件类似这样:

Error: [512] Value must be 1 or below

这个方法不适合所有的错误。常规错误应当通过使用默认的 PHP 记录系统在服务器上进行记录。

相关推荐:

PHP 异常处理 Exception 类

PHP 错误处理机制

php 错误级别设置方法

The above is the detailed content of Customization of PHP exception handler. 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 and Python: Comparing Two Popular Programming Languages PHP and Python: Comparing Two Popular Programming Languages Apr 14, 2025 am 12:13 AM

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

PHP in Action: Real-World Examples and Applications PHP in Action: Real-World Examples and Applications Apr 14, 2025 am 12:19 AM

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

PHP vs. Python: Understanding the Differences PHP vs. Python: Understanding the Differences Apr 11, 2025 am 12:15 AM

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

PHP's Purpose: Building Dynamic Websites PHP's Purpose: Building Dynamic Websites Apr 15, 2025 am 12:18 AM

PHP is used to build dynamic websites, and its core functions include: 1. Generate dynamic content and generate web pages in real time by connecting with the database; 2. Process user interaction and form submissions, verify inputs and respond to operations; 3. Manage sessions and user authentication to provide a personalized experience; 4. Optimize performance and follow best practices to improve website efficiency and security.

The Future of PHP: Adaptations and Innovations The Future of PHP: Adaptations and Innovations Apr 11, 2025 am 12:01 AM

The future of PHP will be achieved by adapting to new technology trends and introducing innovative features: 1) Adapting to cloud computing, containerization and microservice architectures, supporting Docker and Kubernetes; 2) introducing JIT compilers and enumeration types to improve performance and data processing efficiency; 3) Continuously optimize performance and promote best practices.

PHP vs. Other Languages: A Comparison PHP vs. Other Languages: A Comparison Apr 13, 2025 am 12:19 AM

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

PHP and Python: Different Paradigms Explained PHP and Python: Different Paradigms Explained Apr 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.

See all articles