A detailed explanation of the use of PHP custom error handlers

  • 2020-06-03 06:01:00
  • OfStack


function myErrorHandler($errno, $errstr, $errfile, $errline){
    if(!(error_reporting() &$errno)){return;}
    switch ($errno){
    case E_USER_ERROR:
        echo "<b>My ERROR</b> [$errno] $errstr<br/>";
        echo " Error: $errline  In the file: $errfile Among the <br/>";
        echo " PHP Version:  " .PHP_VERSION ." (" .PHP_OS .")<br/>";
        break;
    case E_USER_WARNING:
        echo "<b>My WARNING</b> [$errno] $errstr<br/>";
        break;
    case E_USER_NOTICE:
        echo "<b>My NOTICE</b> [$errno] $errstr<br />";
        break;
    default:
        echo "Unknown error type: [$errno] $errstr<br />";
        break;
    }
    return true;
}
function trigger_test($age){// A test function that throws an error 
    if($age <= 0 || $age > 999) trigger_error(" Illegal age: $age At the age of ", E_USER_ERROR);
    if($age < 18) trigger_error(" Minor: $age At the age of ", E_USER_WARNING);
    if($age > 40 && $age < 100) trigger_error(" Older age: $age At the age of ", E_USER_NOTICE);
}
// If it's a simple system 1 Handle errors: 
$errorHandler = set_error_handler("myErrorHandler");
trigger_test(1000);// Will be thrown 1 a error With a magnitude of error 

function myError($errno, $errstr, $errfile, $errline){
    print_r(func_get_args());
    // Specific treatment method 
}
function myWarning($errno, $errstr, $errfile, $errline){
    print_r(func_get_args());
    // Specific treatment method 
}
function myNtice($errno, $errstr, $errfile, $errline){
    print_r(func_get_args());
    // Specific treatment method 
}
// If you want to handle different error levels separately: 
set_error_handler('myError',E_USER_ERROR);
set_exception_handler('myWarning',E_USER_WARNING);
set_exception_handler('myNtice',E_USER_NOTICE);
trigger_error(' Throw an error on purpose, or it's serious 1 Kind of! ',E_USER_ERROR);


Related articles: