From 0725d02caeb69ba222c03cfd6e5043de92b53f17 Mon Sep 17 00:00:00 2001 From: Belle Aerni Date: Fri, 28 Oct 2022 23:46:28 -0700 Subject: [PATCH] Box_Exception: log a backtrace when debug enabled --- src/bb-library/Box/Exception.php | 48 +++++++++++++++++++++++++++++++- 1 file changed, 47 insertions(+), 1 deletion(-) diff --git a/src/bb-library/Box/Exception.php b/src/bb-library/Box/Exception.php index c1162c7b6..b85b15b61 100644 --- a/src/bb-library/Box/Exception.php +++ b/src/bb-library/Box/Exception.php @@ -22,10 +22,56 @@ class Box_Exception extends Exception */ public function __construct($message, array $variables = NULL, $code = 0) { + $config = include BB_PATH_ROOT.'/bb-config.php'; + + if(isset($config['debug']) && $config['debug'] === true){ + error_log('An exception has been called. Stacktrace:'); + error_log( $this->stackTrace() ); + } + // Set the message $message = __($message, $variables); // Pass the message to the parent parent::__construct($message, $code); } -} \ No newline at end of file + + /** + * Big thank you to jhurliman and jambroseclarke on Stack Overflow for this backtrace formatter. + * We have slightly modified it for our purposes + * https://stackoverflow.com/a/32365961 + */ + private function stackTrace($Length = 25) { + $stack = debug_backtrace($Length); + $output = ''; + + $stackLen = count($stack); + for ($i = 1; $i < $stackLen; $i++) { + $entry = $stack[$i]; + + $func = $entry['function'] . '('; + if(isset($entry['args'])){ + $argsLen = count($entry['args']); + for ($j = 0; $j < $argsLen; $j++) { + $my_entry = $entry['args'][$j]; + if (is_string($my_entry)) { + $func .= $my_entry; + } + if ($j < $argsLen - 1) $func .= ', '; + } + } + $func .= ')'; + + $entry_file = 'NO_FILE'; + if (array_key_exists('file', $entry)) { + $entry_file = $entry['file']; + } + $entry_line = 'NO_LINE'; + if (array_key_exists('line', $entry)) { + $entry_line = $entry['line']; + } + $output .= $entry_file . ':' . $entry_line . ' - ' . $func . PHP_EOL; + } + return $output; + } +}