Tuesday, 11 September 2018

Triggering errors with PHP

It is possible to trigger an error in PHP. This can be useful for debugging purposes, or if there is some condition which occurs in your PHP script which requires a PHP notice, warning or full error which causes the script to halt execution, and which would not be generated by PHP itself.
The function for doing this is trigger_error(), and it is passed the error message to be displayed and, optionally, the error type. For example:
trigger_error('No database connection');
The above example would issue the default error type (E_USER_NOTICE) and display the following error message. I have made the message we passed to the trigger error function in bold in the example, but it would normally just appear as unbolded plain text.
Notice: No database connection in /path/to/script.php on line 33
There are three different error levels or error types that can be passed to the trigger_error() function and these are as follows:
  • E_USER_ERROR - this is the equivalent of E_ERROR and indicates an error that can not be recovered from. Execution of the script is halted at this point.
  • E_USER_WARNING - this is the equivalent of E_WARNING and issues a warning message. Execution of the script is not halted.
  • E_USER_NOTICE - this is the equivalent of E_NOTICE and issues a notice message. Execution of the script is not halted.
If we called trigger_error() passing in E_USER_WARNING, the result would look like this, and the script would continue running:
trigger_error('No database connection', E_USER_WARNING);
Warning: No database connection in /path/to/script.php on line 33
If we called trigger_error() passing in E_USER_ERROR, the result would look like this, and the script would stop running at this point:
trigger_error('No database connection', E_USER_ERROR);
Fatal error: No database connection in /path/to/script.php on line 33
In later posts I'll look at combining the user of trigger_error() with PHP's custom error handling function set_error_handler(). Read the PHP trigger_error() manual page for more details about the use of trigger_error()

Related posts:

0 comments:

Post a Comment