search
HomeBackend DevelopmentPHP TutorialDo you know how to customize error handling functions and error masking in PHP?

In the previous article, I brought you "Take you to understand the error types and error levels of PHP", which introduced the error types and error levels in PHP in detail. In this article we Let’s take a look at how to customize error handling and how to block errors in PHP. I hope it will be helpful to everyone!

Do you know how to customize error handling functions and error masking in PHP?

In our daily development, it is inevitable to encounter errors. Sometimes we can specify a function as an error handling function. There is a custom error in PHP processing function.

<strong><span style="font-size: 20px;">set_error_handler() </span></strong>##Function custom error handling function

PHP provides the set_error_handler() function, which is used to specify a function as an error handling function. Its syntax format is as follows:

set_error_handler(自定义函数名 [, int $error_types = E_ALL | E_STRICT ])

The syntax format of this custom function name is as follows:

error_handler(int 错误的级别 , string 错误的信息 [, string 发生错误的文件名 [, int 发生错误的行号 ]])

If there is an error handler defined before, the returned program name is the program name of the modified program; if it is a built-in error handler, the returned result is NULL. If an invalid callback function is specified, NULL will also be returned.


Next let’s take a look at an example, customize an error handling function, and use it to handle errors in the program. The example is as follows:


<?php
    function error_handler($errno, $errstr, $errfile, $errline ) {
        echo "error number:".$errno."<br/>";
        echo "error msg:".$errstr."<br/>";
        echo "error file:".$errfile."<br/>";
        echo "error line:".$errline."<br/>";
        die(&#39;something error&#39;);
    }
    set_error_handler("error_handler");
    strpos();
?>

Output results :


Do you know how to customize error handling functions and error masking in PHP?

#What we need to pay attention to when using this function is that we only use this method for error handling. If the function has no errors, or the program does not When running in the wrong function, the program will continue to execute the function statement where the error occurred, so we need to use the die() function to terminate the function.


In our daily development, exceptions in the program cannot be thrown automatically. At this time, we can also use set_error_handler() to customize and handle the exception as an error, so that we can use Customize error handling to automatically catch exceptions.

The example is as follows:

<?php
    function error_handler($errno, $errstr, $errfile, $errline ) {
        echo "error number:".$errno."<br/>";
        echo "error msg:".$errstr."<br/>";
        echo "error file:".$errfile."<br/>";
        echo "error line:".$errline."<br/>";
        die(&#39;something error&#39;);
    }
    set_error_handler("error_handler");
    /* 触发异常 */
    try {
        $a = 5/0;//程序会自动捕捉这个异常,并且由自定义函数来处理
        echo $a;
    } catch(Exception $e) {
        echo $e->getMessage();
    }
?>

Output result:


Do you know how to customize error handling functions and error masking in PHP?

##Error maskingIn the PHP development process, we can not only handle errors by customizing the error handling function through set_error_handler(), but we can also mask errors. In some cases, error masking is also essential. Next, I will list some methods for error shielding.

  • @<span style="font-size: 16px;"><strong></strong></span>##---Error control operator

    In PHP, if the error control operator @ is placed in front of an expression, any errors that may exist in the expression will be blocked.

Regarding the use of @, we need to note that the @ operator will only take effect when placed in front of an expression. For example, the @ operator can be used in front of variables, functions, constants, etc. , must not be placed before the definition of a function or class, nor can it be placed in front of a conditional structure statement.

The example is as follows:

<?php
    $link = @mysqli_connect("127.0.0.1", "my_user", "my_password", "my_db") or die(&#39;数据库连接失败!&#39;);
?>

Output result:


In the above example, it can be seen that @ Error control operator, which can mask expressions before expressions. Do you know how to customize error handling functions and error masking in PHP?

  • Use

    error_reporting() Function to shield errors##PHP There are many error levels in PHP. You can use the error_reporting() function to set what kind of errors PHP will report. The syntax format of the function is as follows:

    error_reporting(设置错误级别)
  • Regarding the error levels, please learn about them in the previous article "
PHP's error types and error levels are introduced in more detail. Next, let's look at the use of functions through examples:

<?php
    error_reporting(0);
    $link = mysqli_connect("127.0.0.1", "my_user", "my_password", "my_db") or die(&#39;数据库连接失败!&#39;);
?>

Output results:


Do you know how to customize error handling functions and error masking in PHP?
##Mask errors through the

display_errors
    parameter
  • This method is the most thorough method. The first two methods only work on a single line or a single file, but masking errors through the display_errors parameter works on all PHP files. Let’s take a look at what to do. Do it. First we need to open the

    php.ini
  • configuration file, then find display_errors, set its value to Off to turn off all PHP error reports.

(In the previous article "How to upload files in PHP? You will understand after reading it!" introduced the relevant knowledge on how to remove php and ini configuration files)

Examples are as follows:

Do you know how to customize error handling functions and error masking in PHP?

This way you can block errors.

If you are interested, you can click on "PHP Video Tutorial" to learn more about PHP knowledge.

The above is the detailed content of Do you know how to customize error handling functions and error masking in PHP?. 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
How to make PHP applications fasterHow to make PHP applications fasterMay 12, 2025 am 12:12 AM

TomakePHPapplicationsfaster,followthesesteps:1)UseOpcodeCachinglikeOPcachetostoreprecompiledscriptbytecode.2)MinimizeDatabaseQueriesbyusingquerycachingandefficientindexing.3)LeveragePHP7 Featuresforbettercodeefficiency.4)ImplementCachingStrategiessuc

PHP Performance Optimization Checklist: Improve Speed NowPHP Performance Optimization Checklist: Improve Speed NowMay 12, 2025 am 12:07 AM

ToimprovePHPapplicationspeed,followthesesteps:1)EnableopcodecachingwithAPCutoreducescriptexecutiontime.2)ImplementdatabasequerycachingusingPDOtominimizedatabasehits.3)UseHTTP/2tomultiplexrequestsandreduceconnectionoverhead.4)Limitsessionusagebyclosin

PHP Dependency Injection: Improve Code TestabilityPHP Dependency Injection: Improve Code TestabilityMay 12, 2025 am 12:03 AM

Dependency injection (DI) significantly improves the testability of PHP code by explicitly transitive dependencies. 1) DI decoupling classes and specific implementations make testing and maintenance more flexible. 2) Among the three types, the constructor injects explicit expression dependencies to keep the state consistent. 3) Use DI containers to manage complex dependencies to improve code quality and development efficiency.

PHP Performance Optimization: Database Query OptimizationPHP Performance Optimization: Database Query OptimizationMay 12, 2025 am 12:02 AM

DatabasequeryoptimizationinPHPinvolvesseveralstrategiestoenhanceperformance.1)Selectonlynecessarycolumnstoreducedatatransfer.2)Useindexingtospeedupdataretrieval.3)Implementquerycachingtostoreresultsoffrequentqueries.4)Utilizepreparedstatementsforeffi

Simple Guide: Sending Email with PHP ScriptSimple Guide: Sending Email with PHP ScriptMay 12, 2025 am 12:02 AM

PHPisusedforsendingemailsduetoitsbuilt-inmail()functionandsupportivelibrarieslikePHPMailerandSwiftMailer.1)Usethemail()functionforbasicemails,butithaslimitations.2)EmployPHPMailerforadvancedfeatureslikeHTMLemailsandattachments.3)Improvedeliverability

PHP Performance: Identifying and Fixing BottlenecksPHP Performance: Identifying and Fixing BottlenecksMay 11, 2025 am 12:13 AM

PHP performance bottlenecks can be solved through the following steps: 1) Use Xdebug or Blackfire for performance analysis to find out the problem; 2) Optimize database queries and use caches, such as APCu; 3) Use efficient functions such as array_filter to optimize array operations; 4) Configure OPcache for bytecode cache; 5) Optimize the front-end, such as reducing HTTP requests and optimizing pictures; 6) Continuously monitor and optimize performance. Through these methods, the performance of PHP applications can be significantly improved.

Dependency Injection for PHP: a quick summaryDependency Injection for PHP: a quick summaryMay 11, 2025 am 12:09 AM

DependencyInjection(DI)inPHPisadesignpatternthatmanagesandreducesclassdependencies,enhancingcodemodularity,testability,andmaintainability.Itallowspassingdependencieslikedatabaseconnectionstoclassesasparameters,facilitatingeasiertestingandscalability.

Increase PHP Performance: Caching Strategies & TechniquesIncrease PHP Performance: Caching Strategies & TechniquesMay 11, 2025 am 12:08 AM

CachingimprovesPHPperformancebystoringresultsofcomputationsorqueriesforquickretrieval,reducingserverloadandenhancingresponsetimes.Effectivestrategiesinclude:1)Opcodecaching,whichstorescompiledPHPscriptsinmemorytoskipcompilation;2)DatacachingusingMemc

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 Article

Hot Tools

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)