Tag Archives: User Defined

User Defined Errors

• Userland code may trigger custom errors

trigger_error(
 "something went wrong",
 E_USER_WARNING);

• These errors may be handled with a custom error handler function

function myHandler($code, $text, $file, $line) {
 
 if ($code == E_USER_WARNING) {
 echo 'WARNING: ' .
 htmlspecialchars($text);
 return true;
 }
 
 return false;
}

• If the custom error handler function returns true, php´s error handling does not kick in

• Custom error handler function needs to be registered using set_error_handler(“myHandler”).

Example

<?php
 function myErrorHandler($errno, $errstr, $errfile, $errline) {
 echo "<b>Custom error:</b> [$errno] $errstr<br>";
 echo " Error on line $errline in $errfile<br>";
 }

set_error_handler("myErrorHandler");
 
 $test=2;

if ($test>1) {
 trigger_error("A custom error has been triggered");
 }
?>