How to avoid “memory … exhausted” error when using debug_backtrace() in custom error handler?

Nate picture Nate · Jul 23, 2014 · Viewed 8.1k times · Source

I wrote an error handler for my website that looks like this:

function errorHandler($number, $string, $file, $line, $context, $type = '') {
// save stuff in DB
}

Which I register like this:

set_error_handler('errorHandler', E_ALL);

I save all of the passed variables in a DB, as well as a backtrace to help me debug the problem:

print_r(debug_backtrace(DEBUG_BACKTRACE_PROVIDE_OBJECT), true)

The problem is that I sometimes get this error:

Allowed memory size of 134217728 bytes exhausted (tried to allocate 30084081 bytes)

The reason the error handler was run when it gave the above error was that I tried to use an undefined variable after having created an Amazon S3 object (from their PHP AWS library). I'm assuming since the Amazon AWS library is so huge that the backtrace is pulling in a ton of data, which causes the out of memory error (?).

I want to include a backtrace when possible to help with debugging, but how do I prevent calling the debug_backtrace() function from causing a fatal error (inside my error handler, which is kind of ironic..)?

Answer

edmondscommerce picture edmondscommerce · Jul 30, 2014

I suspect you simply need to remove the DEBUG_BACKTRACE_PROVIDE_OBJECT

It could be that your code has circular references in the objects that mean that when dumping them it loops until all memory is consumed.

Another alternative way to do this is to throw and catch an Exception and then use this to get your backtrace

try{
  throw new Exception();
}catch(Exception $e){
  echo $e->getTraceAsString();
}

http://php.net/manual/en/exception.gettraceasstring.php

Or if you need verbosity then try print_r($e->getTrace());

http://php.net/manual/en/exception.gettrace.php