Customization of PHP exception handler
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 记录系统在服务器上进行记录。
相关推荐:
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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



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,

In PHP8, match expressions are a new control structure that returns different results based on the value of the expression. 1) It is similar to a switch statement, but returns a value instead of an execution statement block. 2) The match expression is strictly compared (===), which improves security. 3) It avoids possible break omissions in switch statements and enhances the simplicity and readability of the code.

In PHP, you can effectively prevent CSRF attacks by using unpredictable tokens. Specific methods include: 1. Generate and embed CSRF tokens in the form; 2. Verify the validity of the token when processing the request.

PS card is "Loading"? Solutions include: checking the computer configuration (memory, hard disk, processor), cleaning hard disk fragmentation, updating the graphics card driver, adjusting PS settings, reinstalling PS, and developing good programming habits.

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.

Strict types in PHP are enabled by adding declare(strict_types=1); at the top of the file. 1) It forces type checking of function parameters and return values to prevent implicit type conversion. 2) Using strict types can improve the reliability and predictability of the code, reduce bugs, and improve maintainability and readability.

In PHP, the final keyword is used to prevent classes from being inherited and methods being overwritten. 1) When marking the class as final, the class cannot be inherited. 2) When marking the method as final, the method cannot be rewritten by the subclass. Using final keywords ensures the stability and security of your code.

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.
