trigger_error

(PHP 4 >= 4.0.1, PHP 5)

trigger_error -- Generates a user-level error/warning/notice message

说明

bool trigger_error ( string error_msg [, int error_type] )

Used to trigger a user error condition, it can be used by in conjunction with the built-in error handler, or with a user defined function that has been set as the new error handler (set_error_handler()).

This function is useful when you need to generate a particular response to an exception at runtime.

参数

error_msg

The designated error message for this error. It's limited to 1024 characters in length. Any additional characters beyond 1024 will be truncated.

error_type

The designated error type for this error. It only works with the E_USER family of constants, and will default to E_USER_NOTICE.

返回值

This function returns FALSE if wrong error_type is specified, TRUE otherwise.

范例

例子 1. trigger_error() example

See set_error_handler() for a more extensive example.

<?php
if (assert($divisor == 0)) {
    
trigger_error("Cannot divide by zero", E_USER_ERROR);
}
?>


add a note add a note User Contributed Notes
richard at 2006 dot atterer dot net
04-Apr-2006 12:28
Beware, trigger_error() is absolutely useless for transporting your own function's error messages in $php_errormsg:

ini_set('track_errors', TRUE);
function x() { trigger_error('MY ERROR'); }
@x();
echo "Error 1: \\"$php_errormsg\\"\\n";
@file_get_contents('/nonexisting');
echo "Error 2: \\"$php_errormsg\\"\\n";

This outputs:

Error 1: ""
Error 2: "failed to open stream: No such file or directory"

This behaviour is consistent with the description of $php_errormsg, which says that the variable will only be available within the scope in which the error occurred. The problem can be worked around with a custom error handler like the one below. However, I'm undecided whether changing the language in this way is good:

function errHandler($errno, $errstr, $errfile, $errline) {
  global $php_errormsg; $php_errormsg = $errstr;
}
set_error_handler('errHandler');
mano at easymail dot hu
26-Apr-2005 08:13
I am not so familiar with this but I think you can reach some of the functionality of try..catch with this function. I would disagree or correct the previous note. The @ is not the catch, it sets the error_reporting to 0 tempolary but with set_error_handler you can try to imitate some behavior like catch.
I've just made this to try if it possible, I never tried in projects but I think could work in php 4. Actually if you want to have the Trace of the error you need to use php4.3+.
Maybe not many of you will create new scripts in php4 and try to have some features from php5 but in some cases (extending older projects) this could be better error handling.

If this is a wrong approach, waiting for comments, if its not, use it!

<?
function catch($errno, $errstr, $errfile, $errline){
  
$GLOBALS['throw'] = $errstr;
  
$GLOBALS['throw_info'] = array(
      
'Message'=>$errstr
      
,'Code'=>$errno
      
,'Line'=>$errline
      
,'File'=>$errfile
      
,'Trace'=>debug_backtrace()
   );
  
}
set_error_handler('catch');

function
badgirl(){
   if(
true){ //error occure
      
trigger_error("BadGirlWithError",E_USER_NOTICE); // as throw with notice
      
return; // ...because trigger_error does not stop the function
  
}else{
       return
true;
   }
}

// Try
$GLOBALS['throw'] = null; // ...try...
$sheis = badgirl(); //could be @badgirl, display_errors is something else, this just the handling
// ..try
if($GLOBALS['throw']){  // This actually catch re-throws too...
  
switch($GLOBALS['throw']){ // Catch
      
case 'GoodGirlException':
           die(
'No bad girl today!');
       break;
       case
'BadGirlWithError':
           die(
'Bad girl has some error');
       break;
       default:
           return;
// or you can make another trigger_error and re-throw another 'exception' or some other action
  
}
}
echo
"You will never see this line - @ only supress message, not a control flow";
echo
"Wrong! You could see this:)";

?>

.mano
dzn'tM@ter
21-Jan-2004 01:05
Some might think that trigger_error is like a throw() or an err.raise construction, and @ works like catch(){} one - in fact it's NOT.

function badgirl(){
   trigger_error("shame on me",E_USER_ERROR);
   return true;
}

$sheis = @badgirl();
echo "You will never see this line - @ only supress message, not a control flow";
robert at klugher dot com
24-Sep-2003 08:12
This one took me some time ...

When you use trigger_error with your own error handler, the class instances are destroyed (don't know how to say it better, I am not an expert).

So, if you try to call a class function from within the error handler function, you will get 'Call to a member function on a non-object' error, even if this function works perfectly in the rest of your script.

Solution : re-use the xxx = new yyy to re-create the instance in the beginning of your error handler ... and then you can call the class functions you want !
mail at dooley dot cjb dot net
30-Jul-2003 10:16
i recently began using a custom error handling class. the biggest problem is that, with call time pass by reference deprecated, you can't manipulate the error handler class after assigning at as the error handler (and it appears not to be returned by the set_error_handler method as the old error handler). my goal was to be able to store up all my non-fatal errors and print them at the end of script execution. that way i can use 'trigger_error' (which i actually have wrapped in a static method ErrorHandler::throwException for portability purposes... which is a pain because it always has the same line number information!!) for all kinds of errors, including user input erros. so when i check a user's password, for instance i would trigger a warning that said 'incorrect password'. of course i would only want this to print out the error once the script had completed.

so in my error handler class i have the following in the constructor:

function ErrorHandler()
{
   $this->error_messages  = array();
   error_reporting (E_ALL);
   set_error_handler(array($this,"assignError"));
}

and my assignError method:
//accept the required arguments
function assignError($errno, $errstr, $errfile, $errline)
{
   //get the error string
   $error_message = $errstr;
//if in debug mode, add line number and file info
 if(ErrorHandler::DEBUG())
 $error_message .= "<br>".basename($errfile).",line: ".$errline;

           switch ($errno)
           {
               //if the error was fatal, then add the error
               //display an error page and exit
               case ErrorHandler::FATAL():
                   $this->setType('Fatal');
                   $this->addError($error_message);
                   Display::errorPage($this->errorMessages());
                   exit(1);
               break;
               //if it was an error message, add a message of
               //type error
               case ErrorHandler::ERROR():
                   $this->setType('Error');
                   $this->addError($error_message);
               break;
               //if it was a warning, add a message of type
               //warning
               case ErrorHandler::WARNING():
                   $this->setType('Warning');
                   $this->addError($error_message);
               break;
               //if it was some other code then display all
               //the error messages that were added
               default:
                   Display::errorRows($this->errorMessages());
               break;
           }
           //return a value so that the script will continue
           //execution
           return 1;
}

the key part there is the 'default' behaviour. i found that if i call trigger_error with anything other than E_USER_ERROR, E_USER_WARNING or E_USER_NOTICE, then error code '2' is passed to the handler method. so when it is time to print all my non-fatal errors, like 'password and confirm password don't match' or something, i call ErrorHandler::printAllErrors()

       function printAllErrors()
       {
           trigger_error("",2);
       }

which leads to the default behaviour in my switch statement in the assignError method above. the only problem with this is that the weird bug 'Problem with method call' that occurs with some static method calls (that one person on the bug lists said was fixed and another said wouldn't be fixed until version 5) also produces error code 2!! i have just taken to suppressing these errors with @, because despite the alledged problem with the method call, the script still seems to execute fine.

iain.
someone at attbi dot com
24-May-2003 12:24
sl0th, the idea is never to give out file names, line numbers, and cryptic codes to the user. Use trigger_error() after you used set_error_handler() to register your own callback function which either logs or emails the error codes to you, and echo a simple friendly message to the user.

And turn on a more verbose error handler function when you need to debug your scripts. In my init.php scripts I always have:

if (_DEBUG_) {
   set_error_handler ('debug_error_handler');
}
else {
   set_error_handler ('nice_error_handler');
}
sl0th at r00thell dot ath dot cx
21-May-2003 10:25
Well this is a good way on debuging your php scripts, but i wouldn't feel
too comfortable by giving out my web servers structure.
Notice that what helps you finding and isolating errors in your php helps also a potential attacker.
Or maybe i am just paranoid, but its worth mention it.
ceo at l-i-e dot com
29-Oct-2002 09:20
You should be using set_error_handler (possibly in conjuction with error_log and/or trigger_error) if you want FILE and LINE number information.
You don't need macros for this.
jason at lehighweb dot com
16-Jul-2001 03:28
Fatal error: Cannot divide by zero in
/home/phpwebmaster/public_html/test2.php on line 11

That almost looks evil, doesn't it?  Except that I made PHP print that out.

You see, most of use apply echo() style error checking in PHP, when in fact we could be using the trigger_error() function.

For example:

<?php
$divisor
=;
if (
assert ($divisor =0))
  
trigger_error ("Cannot divide by zero", E_USER_ERROR);
?>

That will print out a PHP like error, making it easy to find errors in your logic.  It will print out the page, and the line number that the trigger_error() function is called on.  A handly little tool in debugging, as well as controlling error messages.  It also looks much more
prefossional than

echo "Cannot divide by zero"

Happy coding!

Note: This was taken directy from the PHP Newsletter located here: http://www.newbienetwork.net