Error handling mechanism in php

There is a set of error handling mechanism in php, you can use set_error_handler to take over php error handling, or you can use trigger_error function to actively throw an error.

 

The set_error_handler() function sets a user-defined error handling function. The function user creates the user's own error handling method during runtime. It needs to create an error handler first, and then set the error level.

grammar:

set_error_handler(error_function, error_types)  

parameter:

error_function: Specifies the function to run when an error occurs. Required.

error_types: Specifies which error reporting level will display user-defined errors. Optional. Default is "E_ALL".

 

Using this function completely bypasses standard php error handling (unless false is returned in error handling).

 

Example:

function customError($errno, $errstr, $errfile, $errline)
{
    echo "Error code: [$errno] $errstr" . PHP_EOL;
    echo "Error at line: $errline file $errfile" . PHP_EOL;
    // the;
}
set_error_handler("customError");

5/0;

  

output:

Error code: [2] Division by zero
The line of code where the error is located: 15 file /xxx/test.php

  

 

One thing to note here is that errors and exceptions in php are not the same. The error in php cannot be caught by try...catch by default. If we want to catch it, we can throw an exception after catching the error in the error handler.

We can also use restore_error_handler in some places to cancel custom error handling.

 

For fatal error:

If we also want to do something with it, php also provides register_shutdown_function, which triggers a function when the php program terminates or dies.

 

For parse error, we can modify php.ini to add configuration:

log_errors=On

error_log=usr/log/php.log

 

Summarize:

In php, errors and exceptions are two different concepts, and this design fundamentally causes exceptions in php to be different from other languages. In Java, exceptions are the only way to report errors. And most exceptions in php must be thrown manually by some method before they can be caught, which is a semi-automatic exception handling mechanism.

Whether it is an error or an exception, the handler can be used to take over the existing processing mechanism of the system.

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325494034&siteId=291194637