views:

196

answers:

4

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?

+2  A: 

XDebug speaks about such a feature here http://xdebug.org/docs/stack_trace

naivists
Which is probably simpler than my method :)Of course you need to have xdebug setup, which can sometimes be a bit of a PITA.
Neil Aitken
+4  A: 

You can define your own error handler using set_error_handler()

In the handler function you can treat each class of error however you want. Here's a basic template that I use, in my case I only want to handle fatal errors, so I ignore notices and warnings.

In your case you could do a backtrace on warnings, or log them however you want

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
    }
}
Neil Aitken
The following error types cannot be handled with a user defined function: **E_ERROR**, E_PARSE, E_CORE_ERROR, E_CORE_WARNING, E_COMPILE_ERROR, E_COMPILE_WARNING, and most of E_STRICT raised in the file where set_error_handler() is called. - But I upvoted nonetheless.
Gordon
Ah, thanks for the info. I normally used this for handling USER_ERROR but wasn't aware it couldn't catch E_ERROR, although it does make sense when you think about it.
Neil Aitken
+5  A: 

See example #1 at http://www.php.net/manual/en/class.errorexception.php

Tor Valamo
That's pretty cool, I never thought of doing it that way.
Neil Aitken
I think this is how PHPUnit does it to turn regular errors, notices and warnings into PHPUnit Framework error/notice/warning exceptions.
Gordon
Don't know if it's "cool", but it's definately the easiest. :P
Tor Valamo
+1  A: 

Have a look at set_error_handler() and include this at the beginning of your scripts or in your bootstrap to just print the stacktrace when E_WARNINGs occur.

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");

For more control over the various types, have a look at the more explicit version posted elsewhere in the answers.

Gordon