PHP and frameworks built from it have many great tools to assist with debugging (I particularly like XDebug) but sometimes you can find yourself in a situation where the "helper" features aren't all that much help ... in my case this was a framework totally determined to output HTML from my commandline script and to only show me 5 lines of stack trace, which wasn't enough for my complex application. I had to look up how to generate a nice stack trace inside an exception handler so here it is in case I want it again some time (future me, you're welcome!)
set_exception_handler(function (Exception $e) {
echo "EXCEPTION " . $e->getMessage() . "\n";
echo "originates: " . $e->getFile() . " (" . $e->getLine() . ")\n";
$backtrace = $e->getTrace();
foreach ($backtrace as $key => $row) {
echo $row['file'] . " (" . $row['line'] . ")\n";
}
exit;
});
This is intended for me to be able to spot the output even in a raft of fairly chatty debug output (although it's very restrained considering my usual **ASCII ART** tendencies). The initial trigger of the exception is stored in the exception itself, and then "how did we get there?" is in the Exception::getTrace() method, so this outputs the originating information and then works back up the stack to give context.
I thought I'd share in case it's useful - strangely we must all be using code like this in places, but I wasn't able to quickly grab an example when I wanted one.