Home >Backend Development >PHP Tutorial >phpmaster | Error Handling in PHP
<span><span><?php </span></span><span><span>$test = 5; </span></span><span><span>if ($test > 1) { </span></span><span> <span>trigger_error('Value of $test must be 1 or less', E_USER_NOTICE); </span></span><span><span>}</span></span>Triggering errors with trigger_error() is useful when you have an error-handling infrastructure in place, allowing you to unify the handling of both custom errors and the errors and warnings raised by PHP. If you want to implement customized error handling strategies like sending an email or logging errors to a database based on their severity, then you’ll need to define custom error handlers using set_error_handler(). The function accepts two arguments: a callback function or static method that will be invoked when the error is raised, and optionally the error level the function/method handles. The signature of the callback is:
handler(int $errno, string $errstr, string $errfile, int $errline, array $errcontext)
<span><span><?php </span></span><span><span>$test = 5; </span></span><span><span>if ($test > 1) { </span></span><span> <span>trigger_error('Value of $test must be 1 or less', E_USER_NOTICE); </span></span><span><span>}</span></span>The above snippet registers an error handler that does the following: when non-fatal errors occur, a record will be inserted into database instead of displaying the error and logging it to a file; When a fatal error occurs, it will be logged in database and terminate your script. There are some limitations to custom error handlers you should be aware of, however. The error handler bypasses PHP’s standard error handling behavior, so it can’t handle errors that may arise within your handler itself. In the event the database server is down, for example, the above function would fail to record the log. Also, the error handler is not able to catch certain internal errors, like E_CORE_ERROR and E_COMPILE_ERROR, or E_STRICT errors in the same file the handler is defined in since those errors occur before the handler has a chance to be registered.
handler(int $errno, string $errstr, string $errfile, int $errline, array $errcontext)If an exception is thrown by the fictitious getDataFromService() method, it will be caught in the catch block and a message will be displayed. If getDataFromService() executes successfully then the flow will pass over the catch block and continue through the rest of the script. Any exceptions that are thrown and not caught will generate an E_FATAL error with the message “Uncaught Exception.” The Exception class offers six different methods to access information about what caused the problem, as shown in the table below.
<span><span><?php </span></span><span><span>$test = 5; </span></span><span><span>if ($test > 1) { </span></span><span> <span>trigger_error('Value of $test must be 1 or less', E_USER_NOTICE); </span></span><span><span>}</span></span>The code above defines two new custom exception types, NameException and EmailException, which can be used to indicate different errors. Then within the try block, the code checks if values have been supplied for the variables $name and $email. If either is empty, then the appropriate exception is thrown using throw. The corresponding catch block is executed which handles the error.
handler(int $errno, string $errstr, string $errfile, int $errline, array $errcontext)
<span><span><?php </span></span><span><span>function errorHandler($errno, $errstr, $errfile, $errline) { </span></span><span> <span>static $db; </span></span><span> <span>if (empty($db)) { </span></span><span> <span>$db = new PDO(DSN, DBUSER, DBPASS); </span></span><span> <span>} </span></span><span> </span><span> <span>$query = "INSERT INTO errorlog (severity, message, filename, lineno, time) VALUES (?, ?, ?, ?, NOW())"; </span></span><span> <span>$stmt = $db->prepare($query); </span></span><span> </span><span> <span>switch ($errno) { </span></span><span> <span>case E_NOTICE: </span></span><span> <span>case E_USER_NOTICE: </span></span><span> <span>case E_DEPRECATED: </span></span><span> <span>case E_USER_DEPRECATED: </span></span><span> <span>case E_STRICT: </span></span><span> <span>$stmt->execute(array("NOTICE", $errstr, $errfile, $errline)); </span></span><span> <span>break; </span></span><span> </span><span> <span>case E_WARNING: </span></span><span> <span>case E_USER_WARNING: </span></span><span> <span>$stmt->execute(array("WARNING", $errstr, $errfile, $errline)); </span></span><span> <span>break; </span></span><span> </span><span> <span>case E_ERROR: </span></span><span> <span>case E_USER_ERROR: </span></span><span> <span>$stmt->execute(array("FATAL", $errstr, $errfile, $errline)); </span></span><span> <span>exit("FATAL error <span><span>$errstr</span> at <span>$errfile</span>:<span>$errline</span>"</span>); </span></span><span> </span><span> <span>default: </span></span><span> <span>exit("Unknown error at <span><span>$errfile</span>:<span>$errline</span>"</span>); </span></span><span> <span>} </span></span><span><span>} </span></span><span> </span><span><span>set_error_handler("errorHandler"); </span></span><span> </span><span><span>$test = 5; </span></span><span><span>if ($test > 1) { </span></span><span> <span>trigger_error("Value of <span><span>$test</span> must be 1 or less"</span>, E_USER_NOTICE); </span></span><span><span>}</span></span>
Error handling in PHP is crucial for maintaining the integrity and functionality of a web application. It helps developers identify and fix issues that may arise during the execution of a script. Without proper error handling, a minor issue can cause significant problems, such as crashing the application or exposing sensitive information to users. It also improves the user experience as it allows developers to control what the user sees when an error occurs, rather than displaying confusing error messages.
By default, PHP sends an error report to the server’s error log and displays an error message on the screen. This behavior is not ideal for a live website because it can reveal sensitive information to the user. Therefore, it’s recommended to change the default error handling settings for a live website.
PHP classifies errors into several types, including fatal errors, warnings, parse errors, and notices. Fatal errors are critical errors, such as calling a non-existent function or writing to a file that isn’t writable. Warnings are non-fatal errors that allow the script to continue running. Parse errors occur when there’s a syntax mistake in the script. Notices are minor errors or possible errors that PHP encounters while executing a script.
PHP provides several functions to customize error handling, such as set_error_handler() and set_exception_handler(). These functions allow you to define custom error handling rules and exceptions. You can specify a custom function to handle errors, which can be useful for logging errors or sending error notifications.
An exception is an event that occurs during the execution of a script that disrupts the normal flow of the script’s instructions. When an exception is thrown, PHP will stop executing the script and start looking for a catch block to handle the exception. If no catch block is found, PHP will display a fatal error and stop executing the script.
PHP provides the try, catch, and finally blocks to handle exceptions. The try block contains the code that may throw an exception. The catch block contains the code to handle the exception. The finally block contains the code that will be executed regardless of whether an exception was thrown or not.
The main difference between errors and exceptions in PHP is how they are handled. Errors are handled by the PHP engine and can be controlled using error reporting settings and custom error handlers. Exceptions, on the other hand, are handled by the script and can be controlled using try, catch, and finally blocks.
You can turn off error reporting in PHP by using the error_reporting() function with 0 as its argument. However, turning off error reporting is not recommended for a live website because it can make it difficult to identify and fix issues.
The @ operator in PHP is used to suppress error messages. When prepended to an expression in PHP, any error messages that might be generated by that expression will be ignored.
PHP provides the error_log() function to send an error message to the server’s error log or to a specified file. This function can be useful for keeping track of errors and debugging. You can also configure PHP to log all errors by changing the log_errors directive in the php.ini file.
The above is the detailed content of phpmaster | Error Handling in PHP. For more information, please follow other related articles on the PHP Chinese website!