From time to time, developers receive warnings or notice level errors. In the case where the warning is located outside of any loop or other nested structure, it’s easy to debug using ex. xdebug or any other tool like this. Things get a little harder when it comes to the loop execution of functions that throw errors. Things get even worse when we’re iterating over a big set of data and it’s hard to tell which element is causing the problem.

As an example, let’s consider the following warning:

Warning:htmlspecialchars() [function.htmlspecialchars]: An invalid multibyte sequence in argument in/var/www/myApp/vendor/twig/twig/lib/Twig/Extension/Core.php on line 977

Now, line 997 in Core.php looks like this:

return htmlspecialchars($string, ENT_QUOTES | ENT_SUBSTITUTE, $charset);

It is important to note that this line is executed multiple times for each element of the 1000 elements array.

Now comes the really handy trick that allows us to pinpoint the troublesome set of data ($string and $charset) and to analyse the source of the problem. Insert this code before the problematic function call:

$data = array($string, $charset);
set_error_handler(function() use ($data){
}, E_ALL);

Then, just run the script again, and upon the first occurrence of a warning, it’ll dump parameters we’ve assigned to the $data array and stop the script execution so that we don’t have to look through too much output.

This little trick saved my day recently and I think it could be useful in most cases when we are unable to debug easily.

Leave a Reply

Your email address will not be published.Required fields are marked *