'PHP: Print caught exception like Xdebug

I have a PHP function which I call when I caught an exception. It accepts that exception as optional parameter, so it can show it for debugging purposes:

public static function notFound($resource, \Exception $exception = null) {
    // [... normal error handling ...]

    if (DEBUG && $exception != null) {
        echo '<br><br><h2>Stacktrace:</h2>';
        print_r($exception);          
    }
    die();
}

What I would like is to display this exception the same way uncaught exceptions and warnings are displayed with xdebug (styled with CSS and HTML, possibly with a different color scheme). Like this (created by echo $exception->getTrace();):

enter image description here

If I use print_r($exception); I get this, which seems to contain at least some of the needed output for xdebug:

enter image description here

I have tried echo $exception->xdebug_message;, var_dump($exception);, and var_dump($exception->xdebug_message);, but none of it worked. The last one seems to be the closed to what I want, but I can't get it to work correctly:

enter image description here

Is there a way to use xdebug styling for caught exceptions?



Solution 1:[1]

Ok, I found a solution in this list of all xdebug functions:

xdebug_print_function_stack($exception);

Solution 2:[2]

Answered here: https://stackoverflow.com/a/24768176/1286814.

In short, you just need to wrap xdebug_message inside a table:

echo '<table>'.$e->xdebug_message.'</table>';

Solution 3:[3]

With newer versions of xdebug you can display caught (and uncaught) exceptions natively with:

xdebug.show_exception_trace = 1

integer xdebug.show_exception_trace = 0

When this setting is set to 1, Xdebug will show a stack trace whenever an Exception or Error is raised - even if this Exception or Error is actually caught.

Error 'exceptions' were introduced in PHP 7.

Or, if you only want to show errors (caught or uncaught), but not Exceptions, use this instead:

xdebug.show_error_trace = 1

integer xdebug.show_error_trace = 0

When this setting is set to 1, Xdebug will show a stack trace whenever an Error is raised - even if this Error is actually caught.

https://xdebug.org/docs/develop#show_error_trace

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 tim
Solution 2 Joe
Solution 3 Buttle Butkus