百科狗-知识改变命运!
--

trigger_error() - php 错误处理日志函数

乐乐1年前 (2023-11-21)阅读数 14#技术干货
文章标签错误

trigger_error()

(PHP 4 >= 4.0.1, PHP 5, PHP 7)

产生一个用户级别的 error/warning/notice 信息

说明

trigger_error(string $error_msg[,int $error_type= E_USER_NOTICE]): bool

用于触发一个用户级别的错误条件,它能结合内置的错误处理器所关联,或者可以使用用户定义的函数作为新的错误处理程序(set_error_handler())。

该函数在你运行出现异常时,需要产生一个特定的响应时非常有用。

参数

$error_msg

trigger_error() - php 错误处理日志函数

该 error 的特定错误信息,长度限制在了 1024 个字节。超过 1024 字节的字符都会被截断。

$error_type

该 error 所特定的错误类型。仅 E_USER 系列常量对其有效,默认是E_USER_NOTICE

返回值

如果指定了错误的$error_type会返回FALSE,正确则返回TRUE

范例

Example #1trigger_error()示例

set_error_handler()可见到更多详细的例子。

注释

Warning

在$error_msg里的HTML实体并不会被转义。如果错误消息要显示在浏览器里,需要对错误消息使用htmlentities()。

参见

  • error_reporting() 设置应该报告何种 PHP 错误
  • set_error_handler() 设置用户自定义的错误处理函数
  • restore_error_handler() 还原之前的错误处理函数
  • The错误级别常量
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');
}
trigger_error always reports the line and file that trigger_error was called on. Which isn't very useful.
eg:
main.php:

functions.php:

will output "Notice: var must be numeric in functions.php on line 6"
whereas "Notice: var must be numeric in main.php on line 4" would be more useful
here's a function to do that:

So now in our example:
main.php:

functions.php:

now outputs:
"Notice: var must be numeric in doFunction called from main.php on line 4"
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 .= "
".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.
If error_type is E_USER_ERROR then trigger_error throw FATAL ERROR and script stopped after this line. 
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');
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";
For those of you wanting one (or more) lines of context on your call to trigger_error, I offer this. Would be nice to use \n to get a proper stack trace, but it seems trigger_error escapes it; therefore, I use a comma. 
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.
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.

鹏仔微信 15129739599 鹏仔QQ344225443 鹏仔前端 pjxi.com 共享博客 sharedbk.com

免责声明:我们致力于保护作者版权,注重分享,当前被刊用文章因无法核实真实出处,未能及时与作者取得联系,或有版权异议的,请联系管理员,我们会立即处理! 部分文章是来自自研大数据AI进行生成,内容摘自(百度百科,百度知道,头条百科,中国民法典,刑法,牛津词典,新华词典,汉语词典,国家院校,科普平台)等数据,内容仅供学习参考,不准确地方联系删除处理!邮箱:344225443@qq.com)

图片声明:本站部分配图来自网络。本站只作为美观性配图使用,无任何非法侵犯第三方意图,一切解释权归图片著作权方,本站不承担任何责任。如有恶意碰瓷者,必当奉陪到底严惩不贷!

内容声明:本文中引用的各种信息及资料(包括但不限于文字、数据、图表及超链接等)均来源于该信息及资料的相关主体(包括但不限于公司、媒体、协会等机构)的官方网站或公开发表的信息。部分内容参考包括:(百度百科,百度知道,头条百科,中国民法典,刑法,牛津词典,新华词典,汉语词典,国家院校,科普平台)等数据,内容仅供参考使用,不准确地方联系删除处理!本站为非盈利性质站点,本着为中国教育事业出一份力,发布内容不收取任何费用也不接任何广告!)