PHP: 像 Xdebug 一样打印捕捉到的异常

PHP: Print caught exception like Xdebug

我有一个 PHP 函数,当我发现异常时调用它。它接受该异常作为可选参数,因此它可以出于调试目的显示它:

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();
}

我想要显示此异常的方式与使用 xdebug 显示未捕获的异常和警告的方式相同(样式为 CSS 和 HTML,可能具有不同的配色方案)。像这样(由 echo $exception->getTrace(); 创建):

如果我使用 print_r($exception); 我会得到这个,它似乎至少包含一些 xdebug 所需的输出:

我已经尝试了 echo $exception->xdebug_message;var_dump($exception);var_dump($exception->xdebug_message);,但其中 none 有效。最后一个似乎关闭了我想要的,但我无法让它正常工作:

有没有办法对捕获的异常使用 xdebug 样式?

好的,我在 all xdebug functions 的列表中找到了解决方案:

xdebug_print_function_stack($exception);

在这里回答:。

简而言之,你只需要将 xdebug_message 包裹在 table 中:

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

使用较新版本的 xdebug,您可以通过以下方式原生显示已捕获(和未捕获)的异常:

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.

或者,如果您只想显示错误(已捕获或未捕获),而不是异常,请改用此方法:

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