search
HomeBackend DevelopmentPHP TutorialCustomization of PHP exception handler

Customization of PHP exception handler

Dec 23, 2017 pm 03:18 PM
phpprocessorabnormal

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();
}

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);
?>

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);
}
?>

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);
}
?>

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

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
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

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

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

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment