17

I have a php application that I have just re-factored. Unfortunately it spewing out warnings like:

Warning: preg_match() expects parameter 2 to be string, object given in /home/yacoby/dev/netbeans/php/Zend/Db/Select.php on line 776

Which is impossible (or very hard work) to work out the issue as I don't have a callstack so can't tell which parts of my code are causing the warning and there is a lot of code.

I need a method to either treat warnings like errors (In that the application dies and prints the stacktrace) or I need the stacktrace to be shown when printing errors. Is there a method to do this?

4

3 回答 3

25

请参阅http://www.php.net/manual/en/class.errorexception.php上的示例 #1

<?php
function exception_error_handler($errno, $errstr, $errfile, $errline ) {
    throw new ErrorException($errstr, $errno, 0, $errfile, $errline);
}
set_error_handler("exception_error_handler");

/* Trigger exception */
strpos();
?>
于 2010-01-15T11:22:00.037 回答
10

查看set_error_handler()并将其包含在脚本的开头或引导程序中,以便在 E_WARNING 发生时仅打印堆栈跟踪。

function stacktrace_error_handler($errno,$message,$file,$line,$context)
{
    if($errno === E_WARNING) {
        debug_print_backtrace();
    }
    return false; // to execute the regular error handler
}
set_error_handler("stacktrace_error_handler");

要更好地控制各种类型,请查看答案中其他地方发布的更明确的版本。

于 2010-01-15T11:30:31.077 回答
4

您可以使用 set_error_handler() 定义自己的错误处理程序

在处理程序函数中,您可以根据需要处理每一类错误。这是我使用的一个基本模板,在我的例子中,我只想处理致命错误,所以我忽略了通知和警告。

在您的情况下,您可以对警告进行回溯,或者根据需要记录它们

function error_handler($errno,$message,$file,$line,$context) {

switch($errno) {
    // ignore warnings and notices
    case E_WARNING:
    case E_NOTICE:
    case E_USER_NOTICE:
    case E_USER_WARNING:
        break;
    // log PHP and user errors
    case E_ERROR:
    case E_USER_ERROR:
              // Do some processing on fatal errors
    }
}
于 2010-01-15T11:21:35.883 回答