PHP Error and Exception Handling
Errors in PHP:
In most cases, errors in PHP are caused by incorrect syntax or server environment, making the compiler unable to pass the check or even unable to run. Warnings and notices are both errors, just at different levels, and errors cannot be caught by try-catch.
Exceptions in PHP:
Exceptions occur when the program runs into unexpected situations. They are allowed to happen (though you don't want them to), but they are abnormal situations that should not occur in normal logic. These are logic and business process errors, not compilation or syntax errors. We call these exceptions.
The above are the concepts of errors and exceptions in PHP. Any internal error or abnormal code in PHP is treated as an error, not thrown as an exception. However, in some cases, both an exception and an error may be thrown. For example, you cannot automatically catch an exception when a database connection fails, because that's an error, not an exception.
- Error Levels
To handle errors, you must clarify the error levels:
Fatal Error: (Script terminates)
E_ERROR // Fatal runtime error, unrecoverable, script execution stops
E_CORE_ERROR // Fatal error during PHP startup initialization
E_COMPILE_ERROR // Fatal compile-time error, like E_ERROR generated by Zend engine
E_USER_ERROR // User-generated error message, e.g., trigger_error with E_USER_ERROR
Parse Error: (Script terminates)
E_PARSE // Syntax parse error at compile time
Warning Error: (Only gives a warning, script continues)
E_WARNING // Runtime warning (non-fatal)
E_CORE_WARNING // Warning during PHP startup (non-fatal)
E_COMPILE_WARNING // Compile warning
E_USER_WARNING // User-generated warning
Notice Error: (Only gives a notice, script continues)
E_NOTICE // Runtime notice, script encounters something that could be an error
E_USER_NOTICE // User-generated notice
There are 5 types that generate ERROR-level errors, which directly cause the PHP program to exit.
- Simple Error Handling:
When PHP code runs and an error occurs, the system's error handling mechanism is triggered. If error reporting is configured, the error will be reported directly. For example:
If this happens in production, it may expose a lot of information (such as server system), so we usually do some simple configuration:
First: Modify the php.ini configuration file:
error_reporting = E_ALL //Report every error to PHP
display_errors = Off //Do not display error reports
log_errors = On //Enable error logging
log_errors_max_log = 1024 //Max length of each log
error_log = G:/myerror.log //Specify error log file
Note: Since we turned off error reporting, errors still exist. To troubleshoot, we enable error logging.
Second: Handle in code without modifying the config file
error_reporting(E_ALL); //Report every error to PHP
ini_set('display_errors',0); //Do not display error reports
ini_set('log_errors',1); //Enable error logging
ini_set('error_log','./error.log'); //Specify error log file
test();
After running the above code, you will find an error.log file in the current directory, with content like:
[05-Jul-2018 03:37:38 UTC] PHP Fatal error: Uncaught Error: Call to undefined function test() in D:\phpStudy\WWW\test.php:6
Stack trace:
#0 {main}
thrown in D:\phpStudy\WWW\test.php on line 6
- Simple PHP Exception Handling
function checkNum($number)
{
return 100/$number;
}
As shown above: when calling checkNum(), if the parameter is 0, an exception will occur. In this case, we use exception handling:
function checkNum($number)
{
if($number==0) {
throw new Exception("Parameter cannot be 0");
}
return 100/$number;
}
Then when calling:
<?php
try {
checkNum(2);
echo 'Success';
} //Catch exception
catch (Exception $e) {
echo 'Error message: ' . $e->getMessage();
}
Another example of exception handling:
<?php
$pdo = new PDO('mysql://host=wrong_host;dbname=wrong_name');
$count = $pdo->exec("DELETE FROM fruit WHERE colour = 'red'");
When connecting to the database and executing a delete, you can't guarantee the address and username are correct, so use exception handling to optimize the code:
try {
$pdo = new PDO('mysql://host=wrong_host;dbname=wrong_name');
$count = $pdo->exec("DELETE FROM fruit WHERE colour = 'red'");
} catch (PDOException $e) {
$code = $e->getCode();
$message = $e->getMessage();
echo 'Sorry, the service is busy, please try again later';
exit;
}
Exception is the base class for all exceptions. It provides the following methods for handling exceptions:
Exception::getMessage — Get exception message
Exception::getPrevious — Get previous exception in the chain
Exception::getCode — Get exception code
Exception::getFile — Get file where exception was created
Exception::getLine — Get line number where exception was created
Exception::getTrace — Get exception trace info
Exception::getTraceAsString — Get exception trace info as string
Exception::__toString — Convert exception object to string
Exception::__clone — Exception clone