/** * @param \Exception $exception * @return string * @todo Fix this to get full stack trace */ public static function getExceptionTraceAsString(\Exception $exception) { $ret = ""; $count = 0; foreach ($exception->getTrace() as $trace) { $args = ""; if (isset($trace['args'])) { $args = array(); foreach ($trace['args'] as $arg) { if (is_string($arg)) { $args[] = "'" . $arg . "'"; } elseif (is_array($arg)) { $args[] = "Array"; } elseif (is_null($arg)) { $args[] = 'NULL'; } elseif (is_bool($arg)) { $args[] = $arg ? "true" : "false"; } elseif (is_object($arg)) { $args[] = get_class($arg); } elseif (is_resource($arg)) { $args[] = get_resource_type($arg); } else { $args[] = $arg; } } $args = join(", ", $args); } $ret .= sprintf("#%s %s(%s): %s(%s)\n", $count, isset($trace['file']) ? $trace['file'] : 'unknown file', isset($trace['line']) ? $trace['line'] : 'unknown line', isset($trace['class']) ? $trace['class'] . $trace['type'] . $trace['function'] : $trace['function'], $args); $count++; } return $ret; }
/** * After action. * * @param \CInlineAction $action Action from controller * * @return \Docolight\Http\Response */ public function afterAction($action) { parent::afterAction($action); // Basic data template $statusCode = 200; $data = array('status' => $statusCode, 'message' => 'Success', 'value' => $this->data); // Let's find an error if ($this->error instanceof Exception) { // throw $this->error; // Basic data template for an exception $statusCode = 500; $data = ['status' => $statusCode, 'message' => 'Error', 'value' => ['code' => $this->error->getCode(), 'message' => $this->error->getMessage()]]; // If exception code is an HTTP resoponse code if ($message = Response::getMessageForCode($this->error->getCode())) { $statusCode = $this->error->getCode(); $data['status'] = $statusCode; $data['message'] = preg_replace('/^\\d+ /', '', $message); } else { if (YII_DEBUG) { $data['value']['stack_trace'] = $this->error->getTrace(); } } } elseif ($this->data instanceof Response) { return $this->data->send(); } return response('json', $statusCode, collect($data), $this->headers)->send(); }
/** * Returns an iterator for the inspected exception's frames. * * @return FrameCollection */ public function getFrames() { if ($this->frames === null) { $frames = $this->exception->getTrace(); // If we're handling an \ErrorException thrown by BooBoo, // get rid of the last frame, which matches the handleError method, // and do not add the current exception to trace. We ensure that // the next frame does have a filename / linenumber, though. if ($this->exception instanceof \ErrorException) { foreach ($frames as $k => $frame) { if (isset($frame['class']) && strpos($frame['class'], 'BooBoo') !== false) { unset($frames[$k]); } } } $this->frames = new FrameCollection($frames); if ($previousInspector = $this->getPreviousExceptionInspector()) { // Keep outer frame on top of the inner one $outerFrames = $this->frames; $newFrames = clone $previousInspector->getFrames(); $newFrames->prependFrames($outerFrames->topDiff($newFrames)); $this->frames = $newFrames; } } return $this->frames; }
public function handleException(Exception $exception) { $msg = "Uncaught Exception: " . $exception->getMessage() . "\n"; $msg .= $exception->getMessage() . "\n"; $msg .= 'Line: ' . $exception->getLine() . " in " . $exception->getFile(); $msg .= "\n\nTrace Summary:\n" . self::traceFormat($exception->getTrace()); if (ERROR_DISPLAY_MODE == 'html') { $msg .= "\nFull Trace: \n" . print_r($exception->getTrace(), 1); } $this->show($msg, $exception->getFile(), $exception->getLine(), $exception->getCode(), 'E_WARNING'); }
/** * * @param mixed $expected * @param mixed $got * @param string $message */ public function assertEquals($expected, $got, $message = '') { $e = new Exception(); $trace = $e->getTrace()[1]; $line = $e->getTrace()[0]['line']; if ($expected !== $got) { echo sprintf(PHP_EOL . '# ASSERTION ERROR: %s::%s (%s) %s' . PHP_EOL . 'expected:%s' . PHP_EOL . 'got:%s' . PHP_EOL, $trace['class'], $trace['function'], $line, $message, var_export($expected, true), var_export($got, true)); } else { echo '.'; } }
/** * Filters stack frames from PHPUnit classes. * * @param Exception $e * @param boolean $filterTests * @param boolean $asString * @return string */ public static function getFilteredStacktrace(Exception $e, $filterTests = TRUE, $asString = TRUE) { if ($asString === TRUE) { $filteredStacktrace = ''; } else { $filteredStacktrace = array(); } $groups = array('DEFAULT'); if (!defined('PHPUNIT_TESTSUITE')) { $groups[] = 'PHPUNIT'; } if ($filterTests) { $groups[] = 'TESTS'; } if ($e instanceof PHPUnit_Framework_SyntheticError) { $eTrace = $e->getSyntheticTrace(); } else { $eTrace = $e->getTrace(); } if (!self::frameExists($eTrace, $e->getFile(), $e->getLine())) { array_unshift($eTrace, array('file' => $e->getFile(), 'line' => $e->getLine())); } foreach ($eTrace as $frame) { if (isset($frame['file']) && is_file($frame['file']) && !PHP_CodeCoverage::getInstance()->filter()->isFiltered($frame['file'], $groups, TRUE)) { if ($asString === TRUE) { $filteredStacktrace .= sprintf("%s:%s\n", $frame['file'], isset($frame['line']) ? $frame['line'] : '?'); } else { $filteredStacktrace[] = $frame; } } } return $filteredStacktrace; }
public static function exceptionHandler(\Exception $e) { $fullTrace = $e->getTrace(); if (is_callable(array($e, 'postAction'))) { $e->postAction($e->getMessage(), $e->getCode()); } if (!DC::getProjectConfig('devMode')) { DC::getLogger()->add('Exception: ' . $e->getMessage(), 'exception'); die; } $content = '<div style="font-size: 13px; font-family: Consolas, Menlo, Monaco, monospace;white-space: pre-wrap;">'; $htmlTrace = "<b>\nLast arguments(" . count($fullTrace[0]['args']) . "):</b>\n" . dumpAsString($fullTrace[0]['args']) . "<b>\n\nCall stack:</b>\n<table style='font-size: 13px;'>"; foreach ($fullTrace as $item) { $info = self::compileShortCallee($item); $htmlTrace .= '<tr><td style="color:#666;padding-right:10px;">' . $info['file'] . '</td><td>' . $info['call'] . '</td></tr>'; } $htmlTrace .= '</table>'; $content .= '<div style="background:#c00;color:white;font-weight:bold;padding:5px;margin-bottom: 5px; ">' . $e->getMessage() . '</div>'; $content .= $htmlTrace; $content .= '</div>'; if (DC::getRouter()->getExecutionMode() == Request::MODE_CONSOLE) { $content = strip_tags(str_replace('</td><td>', "\n", $content)) . "\n"; } echo $content; die; }
public function testNew() { $ex = new \Exception(); $traces = $ex->getTrace(); $t = new Trace($traces[0]); $this->AssertSame($t->class, 'BetterErrorTests\\TraceTest'); }
function displayExceptionObject(Exception $e) { echo "\$e = >{$e}<\n"; // calls __toString echo "getMessage: >" . $e->getMessage() . "<\n"; echo "getCode: >" . $e->getCode() . "<\n"; echo "getPrevious: >" . $e->getPrevious() . "<\n"; echo "getFile: >" . $e->getFile() . "<\n"; echo "getLine: >" . $e->getLine() . "<\n"; echo "getTraceAsString: >" . $e->getTraceAsString() . "<\n"; $traceInfo = $e->getTrace(); var_dump($traceInfo); echo "Trace Info:" . (count($traceInfo) == 0 ? " none\n" : "\n"); foreach ($traceInfo as $traceInfoKey => $traceLevel) { echo "Key[{$traceInfoKey}]:\n"; foreach ($traceLevel as $levelKey => $levelVal) { if ($levelKey != "args") { echo " Key[{$levelKey}] => >{$levelVal}<\n"; } else { echo " Key[{$levelKey}]:\n"; foreach ($levelVal as $argKey => $argVal) { echo " Key[{$argKey}] => >{$argVal}<\n"; } } } } }
/** * @param Exception $exception * @param Report $report */ protected function _processTrace(Report $report) { foreach ($this->exception->getTrace() as $t) { $aeTrace = new Traceback(); $aeTrace->setFile(isset($t['file']) ? $t['file'] : 'unknown'); $aeTrace->setFn(isset($t['class']) ? "{$t['class']}->{$t['function']}" : $t['function']); $aeTrace->setLine(isset($t['line']) ? $t['line'] : 0); $aeArgs = array(); foreach ($t['args'] as $arg) { $aeArgs[] = $arg; } $aeTrace->setVars(json_encode($aeArgs)); $report->addTraceback($aeTrace); unset($aeTrace); } }
/** * Ставим хук на вызов неизвестного метода и считаем что хотели вызвать метод какого либо модуля * @see Engine::_CallModule * * @param $sName * @param $aArgs * * @return mixed * @throws Exception */ public function __call($sName, $aArgs) { // Ввзовом метода модуля считаем, если есть подчеркивание и оно не в начале if (strpos($sName, '_')) { return E::getInstance()->_CallModule($sName, $aArgs); } else { // Если подчеркивания нет, то вызов несуществующего метода $oException = new Exception('Method "' . $sName . '" not exists in class "' . get_class($this) . '"'); $aStack = $oException->getTrace(); if (!$aStack) { $aStack = debug_backtrace(); } // Инвертируем стек вызовов $aStack = array_reverse($aStack); // И пытаемся определить, откуда был этот некорректный вызов foreach ($aStack as $aCaller) { if (isset($aCaller['file']) && isset($aCaller['function'])) { if (preg_match('/[A-Z]\\w+\\_' . preg_quote($sName) . '/', $aCaller['function']) || $aCaller['function'] == $sName) { $oException->sAdditionalInfo = 'In file ' . $aCaller['file']; if (isset($aCaller['line'])) { $oException->sAdditionalInfo .= ' on line ' . $aCaller['line']; } break; } } } throw $oException; } }
function getExceptionTraceAsString(Exception $exception) { $rtn = ""; $count = 0; foreach ($exception->getTrace() as $frame) { $args = ""; if (isset($frame['args'])) { $args = array(); foreach ($frame['args'] as $arg) { if (is_string($arg)) { $args[] = "'" . $arg . "'"; } elseif (is_array($arg)) { $args[] = json_encode($arg); } elseif (is_null($arg)) { $args[] = 'NULL'; } elseif (is_bool($arg)) { $args[] = $arg ? "true" : "false"; } elseif (is_object($arg)) { $args[] = get_class($arg); } elseif (is_resource($arg)) { $args[] = get_resource_type($arg); } else { $args[] = $arg; } } $args = join(", ", $args); } $rtn .= sprintf("#%s %s(%s): %s%s(%s)\n", $count, $frame['file'], $frame['line'], isset($frame['class']) ? $frame['class'] . '->' : '', $frame['function'], $args); $count++; } return $rtn; }
/** * * @param Exception $exception */ public static function catchException($exception) { $code = $exception->getCode(); $errorController = 'app\\controllers\\ErrorController'; $result = ClassLoader::load($errorController, false); if ($result && class_exists($errorController)) { $controllerObj = new $errorController(new \radium\net\http\Request()); $action = 'index'; $controllerObj->_render['template'] = $action; $controllerObj->invokeMethod('_init'); $data = call_user_func_array(array($controllerObj, $action), array($exception)); $contentType = 'text/html'; $output = ''; if (is_string($data)) { $output = $data; $contentType = 'text/plain'; } else { $controllerObj->invokeMethod('_finalize', $data ? array($data) : array()); $output = $controllerObj->renderedContent(); $contentType = $controllerObj->view->contentType(); } header('Content-Type: ' . $contentType . '; charset=UTF-8'); echo $output; exit; } $backtrace = $exception->getTrace(); $line = array_shift($backtrace); while ($line && !isset($line['file'])) { $line = array_shift($backtrace); } header('Content-Type: text/plain; charset=UTF-8'); echo StringUtil::getLocalizedString('Exception was thrown. ({1}): {2} at {3} line {4} ({5} line {6})', array($code, $exception->getMessage(), $line['file'], $line['line'], $exception->getFile(), $exception->getLine())) . "\n"; exit; }
/** * Sends a response for the given Exception. * * If you have the Symfony HttpFoundation component installed, * this method will use it to create and send the response. If not, * it will fallback to plain PHP functions. * * @param \Exception $exception An \Exception instance * * @see sendPhpResponse * @see createResponse */ public function handle(\Exception $exception) { if ($this->logger !== null) { $this->logger->error($exception->getMessage()); } if ($this->logger_trace !== null) { $string = $exception->getMessage() . "\r\n"; foreach ($exception->getTrace() as $trace) { $string .= ' '; if (isset($trace['file'])) { $string .= 'at ' . $trace['file'] . '(' . $trace['line'] . ') '; } if (isset($trace['class'])) { $string .= 'in ' . $trace['class'] . $trace['type']; } if (isset($trace['function'])) { $string .= $trace['function'] . '(' . $this->stringify($trace['args']) . ')'; } $string .= "\r\n"; } $this->logger_trace->error($string); } if (class_exists('Symfony\\Component\\HttpFoundation\\Response')) { $this->createResponse($exception)->send(); } else { $this->sendPhpResponse($exception); } }
/** * Handle uncaught exceptions. * * @param \Exception $exception An uncaught exception. */ public static function exception_handler(\Exception $exception) { global $CFG, $USR; $errcode = $exception->getCode(); $errmsg = $exception->getMessage(); $errcodelabel = $exception instanceof \pdyn\base\Exception ? $exception->get_string_from_code($errcode) : static::getinternalerrorlabel($errcode); if (\pdyn\base\Utils::is_cli_env() === true) { echo 'APP ERROR: ' . $errcodelabel . ': ' . $errmsg . "\n"; } else { // Atlas exceptions' error codes are HTTP status codes, so send one. if ($exception instanceof \pdyn\base\Exception && !empty($errcode) && !headers_sent()) { \pdyn\httputils\Utils::send_status_code($errcode, '', false); } else { \pdyn\httputils\Utils::send_status_code(500, '', false); } $LOG = new \pdyn\log\Logger($CFG->log_general); $LOG->error($errcodelabel . ': ' . $exception); if (isset($_GET['ajax'])) { header('Content-type: application/json'); echo json_encode(['result' => 'fail', 'msg' => $errcodelabel . ': ' . $errmsg]); } else { $debugmode = !empty($CFG) && (bool) $CFG->get('core', 'debugmode', false) === true ? true : false; $isadmin = !empty($USR) && $USR->is_admin === true ? true : false; $backtrace = $isadmin === true || $debugmode === true ? static::format_backtrace($exception->getTrace()) : null; static::write_error_html($errcodelabel, $errmsg, $errcode, $backtrace); } } die; }
/** * Get a backtrace for an exception. * * Optionally limit the number of rows to include with $count, and exclude * Psy from the trace. * * @param \Exception $e The exception with a backtrace. * @param int $count (default: PHP_INT_MAX) * @param bool $includePsy (default: true) * * @return array Formatted stacktrace lines. */ protected function getBacktrace(\Exception $e, $count = null, $includePsy = true) { if ($count === null) { $count = PHP_INT_MAX; } $lines = array(); $trace = $e->getTrace(); array_unshift($trace, array('function' => '', 'file' => $e->getFile() != null ? $e->getFile() : 'n/a', 'line' => $e->getLine() != null ? $e->getLine() : 'n/a', 'args' => array())); if (!$includePsy) { for ($i = count($trace) - 1; $i >= 0; $i--) { $thing = isset($trace[$i]['class']) ? $trace[$i]['class'] : $trace[$i]['function']; if (preg_match('/\\\\?Psy\\\\/', $thing)) { $trace = array_slice($trace, $i + 1); break; } } } for ($i = 0, $count = min($count, count($trace)); $i < $count; $i++) { $class = isset($trace[$i]['class']) ? $trace[$i]['class'] : ''; $type = isset($trace[$i]['type']) ? $trace[$i]['type'] : ''; $function = $trace[$i]['function']; $file = isset($trace[$i]['file']) ? $trace[$i]['file'] : 'n/a'; $line = isset($trace[$i]['line']) ? $trace[$i]['line'] : 'n/a'; $lines[] = sprintf(' %s%s%s() at <info>%s:%s</info>', $class, $type, $function, $file, $line); } return $lines; }
protected function find_error_line(\Exception $exception) { $trace = $exception->getTrace(); $line = "Unknown line"; $case_name = get_class($this); $file = ""; foreach ($trace as $execution_point) { $assert_funcs = ['assert_true', 'assert_false', 'assert_equal', 'assertEqual', 'assertEquals', 'asserTrue', 'assertNotNull']; $file = ""; $function = $execution_point['function']; if (in_array($function, $assert_funcs)) { // print __METHOD__."FOUND IT\n"; // print __METHOD__." function : ". $execution_point['function'] ."\n"; // print __METHOD__." file : ". $execution_point['file'] ."\n"; // print __METHOD__." line : ". $execution_point['line'] ."\n"; $file = $execution_point['file']; $line = $execution_point['line']; break; } // if(isset($execution_point["file"])) // { // $path_info = pathinfo($execution_point["file"]); // $file = $path_info["filename"]; // } // // if($file == $case_name) // { // $line = $execution_point["line"]; // break; // } } // print __METHOD__." line : $line file: $file \n"; return [$line, $file]; // $this->temporal_result->set_error_line($line); }
public function render(\Exception $e) { $trace = $e->getTrace(); $main_cause = array_shift($trace); $index = count($e->getTrace()); if ($e instanceof \ErrorException and count($trace) > 0) { $main_cause = array_shift($trace); $index -= 1; } $dom_main_cause = $this->renderMainCause($index, $e, $main_cause); $dom_traces = $this->renderTraces($trace); $message = $e->getMessage(); $class = get_class($e); $result = "\n <html>\n <head>\n <style>\n body {\n background: #efefef;\n }\n\n .w > h3 {\n font-size: 18px;\n color: #666;\n margin: 10px 0px 20px;\n line-height: 1.5;\n padding: 0px 30px;\n text-align: left;\n }\n\n .w > h4 {\n font-size: 14px;\n color: #aaa;\n margin: 10px 0px 0px;\n }\n\n .w > h3:before,\n .w > h3:after {\n content: '\"';\n position: absolute;\n top: 20px;\n left: 0px;\n opacity: .5;\n display: inline-block;\n padding: 5px;\n font-size: 26px;\n }\n\n .w > h3:after {\n left: auto;\n right: 0px;\n }\n\n .w, .w ul, .w ul li {\n box-sizing: border-box;\n -webkit-box-sizing: border-box;\n -moz-box-sizing: border-box;\n font-family: sans-serif;\n cursor: default;\n position: relative;\n }\n\n .w {\n max-width: 600px;\n margin: 30px auto; \n }\n\n .w ul {\n padding: 0px;\n margin: 0px;\n float: left;\n width: 100%;\n margin-bottom: 50px;\n box-shadow: 0px 5px 10px 0px rgba(0,0,0,.1);\n }\n\n .w ul li {\n padding: 10px 20px 10px 60px;\n float: left;\n clear: both;\n width: 100%;\n background: white;\n font-size: .7em;\n color: #444;\n border-bottom: 1px dashed #efefef;\n list-style-type: none;\n }\n\n .w ul li:last-child {\n border: none;\n }\n\n .w ul li h4 {\n font-size: 1.3em;\n margin: 0px;\n }\n\n\n .w ul li span {\n opacity: .5;\n }\n\n .w ul li h4 span {\n opacity: .5;\n }\n\n .w ul li.m {\n font-size: 1em;\n }\n\n .w ul li:not(.m):hover {\n background: #f7f7f7;\n }\n\n .w ul li em {\n display: inline-block;\n width: 50px;\n text-align: right;\n position: absolute;\n left: 0px;\n top: 10px;\n font-size: 1.3em;\n font-weight: bold;\n opacity: .6;\n }\n </style>\n </head>\n <body>\n <div class='w'>\n <h4>{$class}</h4>\n <h3>{$message}</h3>\n <ul>{$dom_main_cause}{$dom_traces}</ul>\n </div>\n </body>\n </html>\n "; return $result; }
public function handleException(\Exception $exception) { $this->exception = $exception; foreach ($this->exceptions as $e => $closure) { if ($exception instanceof $e) { $closure($this->core); return; } } $code = ' <html> <head> <style> pre {margin: 0;font-size: 11px;color: #515151;background-color: #D0D0D0;padding-left: 30px;} pre b { display: block; padding-top: 10px; padding-bottom: 10px; } .backtrace {border: 1px solid black; margin: 1px;} .file { font-size: 11px; color: green; background-color: white;} .header { color: rgb(105, 165, 80); background-color: rgb(65, 65, 65); padding: 4px 2px; } .step { color: white; } .tracecode { color: rgb(105, 165, 80); } </style> </head> <body>' . $this->createBackTraceCode($exception->getTrace()) . ' </body> </html> '; echo $code; }
/** * @param \Exception $exception * @param array $data * * @return JsonResponse */ protected function createFailJsonResponse(\Exception $exception, $data) { if (!$this->isProdEnv()) { return new JsonResponse(['success' => 'nok', 'error' => $exception->getMessage(), 'trace' => $exception->getTrace(), 'data' => $data]); } return new JsonResponse(['success' => 'nok', 'error' => $exception->getMessage()]); }
/** * Autoload a class * * @param string $class Classname to load * * @return bool */ function CAS_autoload($class) { // Static to hold the Include Path to CAS static $include_path; // Check only for CAS classes if (substr($class, 0, 4) !== 'CAS_') { return false; } // Setup the include path if it's not already set from a previous call if (empty($include_path)) { $include_path = array(dirname(dirname(__FILE__)), dirname(dirname(__FILE__)) . '/../test/'); } // Declare local variable to store the expected full path to the file foreach ($include_path as $path) { $file_path = $path . '/' . str_replace('_', '/', $class) . '.php'; $fp = @fopen($file_path, 'r', true); if ($fp) { fclose($fp); include $file_path; if (!class_exists($class, false) && !interface_exists($class, false)) { die(new Exception('Class ' . $class . ' was not present in ' . $file_path . ' [CAS_autoload]')); } return true; } } $e = new Exception('Class ' . $class . ' could not be loaded from ' . $file_path . ', file does not exist (Path="' . implode(':', $include_path) . '") [CAS_autoload]'); $trace = $e->getTrace(); if (isset($trace[2]) && isset($trace[2]['function']) && in_array($trace[2]['function'], array('class_exists', 'interface_exists'))) { return false; } if (isset($trace[1]) && isset($trace[1]['function']) && in_array($trace[1]['function'], array('class_exists', 'interface_exists'))) { return false; } die((string) $e); }
/** * Handle the exception. Renders the error view using the class' functions. * @param \Exception $exception */ public function handle(\Exception $exception) { \Application::log()->error($exception->getMessage(), $exception->getTrace()); $this->sendHeader($exception); $errorRenderer = new Renderer\ErrorRenderer('Error'); echo $errorRenderer->render($this->getErrorView($exception), ['exception' => $exception]); }
/** * Get a backtrace for an exception. * * Optionally limit the number of rows to include with $count, and exclude * Psy from the trace. * * @param \Exception $e The exception with a backtrace. * @param int $count (default: PHP_INT_MAX) * @param bool $includePsy (default: true) * * @return array Formatted stacktrace lines. */ protected function getBacktrace(\Exception $e, $count = null, $includePsy = true) { if ($cwd = getcwd()) { $cwd = rtrim($cwd, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR; } if ($count === null) { $count = PHP_INT_MAX; } $lines = array(); $trace = $e->getTrace(); array_unshift($trace, array('function' => '', 'file' => $e->getFile() !== null ? $e->getFile() : 'n/a', 'line' => $e->getLine() !== null ? $e->getLine() : 'n/a', 'args' => array())); if (!$includePsy) { for ($i = count($trace) - 1; $i >= 0; $i--) { $thing = isset($trace[$i]['class']) ? $trace[$i]['class'] : $trace[$i]['function']; if (preg_match('/\\\\?Psy\\\\/', $thing)) { $trace = array_slice($trace, $i + 1); break; } } } for ($i = 0, $count = min($count, count($trace)); $i < $count; $i++) { $class = isset($trace[$i]['class']) ? $trace[$i]['class'] : ''; $type = isset($trace[$i]['type']) ? $trace[$i]['type'] : ''; $function = $trace[$i]['function']; $file = isset($trace[$i]['file']) ? $this->replaceCwd($cwd, $trace[$i]['file']) : 'n/a'; $line = isset($trace[$i]['line']) ? $trace[$i]['line'] : 'n/a'; $lines[] = sprintf(' <class>%s</class>%s%s() at <info>%s:%s</info>', OutputFormatter::escape($class), OutputFormatter::escape($type), OutputFormatter::escape($function), OutputFormatter::escape($file), OutputFormatter::escape($line)); } return $lines; }
/** * Returns an error trace * * @param Exception $e * @return string */ function KickstartErrorTrace($e) { $strTrace = '#0: ' . $e->getMessage() . '; File: ' . $e->getFile() . '; Line: ' . $e->getLine() . "\n"; $i = 1; foreach ($e->getTrace() as $v) { if (!(isset($v['function']) && $v['function'] == 'errorHandle')) { if (isset($v['class'])) { $strTrace .= "#{$i}: " . $v['class'] . $v['type'] . $v['function'] . '('; } elseif (isset($v['function'])) { $strTrace .= "#{$i}: " . $v['function'] . '('; } else { $strTrace .= "#{$i}: "; } if (isset($v['args']) && isset($v['function'])) { $parts = array(); foreach ($v['args'] as $arg) { $parts[] = KickstartErrorArg($arg); } $strTrace .= implode(',', $parts) . ') '; } if (isset($v['file']) && isset($v['line'])) { $strTrace .= '; File: ' . $v['file'] . '; Line: ' . $v['line'] . "\n"; } $i++; } } return $strTrace; }
public static function getFilteredStackTrace(Exception $e, $asString = true) { $stackTrace = $asString ? '' : array(); $trace = $e->getPrevious() ? $e->getPrevious()->getTrace() : $e->getTrace(); if ($e instanceof \PHPUnit_Framework_ExceptionWrapper) { $trace = $e->getSerializableTrace(); } foreach ($trace as $step) { if (self::classIsFiltered($step)) { continue; } if (self::fileIsFiltered($step)) { continue; } if (!$asString) { $stackTrace[] = $step; continue; } if (!isset($step['file'])) { continue; } $stackTrace .= $step['file'] . ':' . $step['line'] . "\n"; } return $stackTrace; }
protected function onNotSuccessfulTest(\Exception $e) { if ($e instanceof \PHPUnit_Framework_AssertionFailedError) { throw $e; } if (isset($this->_sqlLoggerStack->queries) && count($this->_sqlLoggerStack->queries)) { $queries = ""; $i = count($this->_sqlLoggerStack->queries); foreach (array_reverse($this->_sqlLoggerStack->queries) as $query) { $params = array_map(function ($p) { if (is_object($p)) { return get_class($p); } else { return "'" . $p . "'"; } }, $query['params'] ?: array()); $queries .= $i + 1 . ". SQL: '" . $query['sql'] . "' Params: " . implode(", ", $params) . PHP_EOL; $i--; } $trace = $e->getTrace(); $traceMsg = ""; foreach ($trace as $part) { if (isset($part['file'])) { if (strpos($part['file'], "PHPUnit/") !== false) { // Beginning with PHPUnit files we don't print the trace anymore. break; } $traceMsg .= $part['file'] . ":" . $part['line'] . PHP_EOL; } } $message = "[" . get_class($e) . "] " . $e->getMessage() . PHP_EOL . PHP_EOL . "With queries:" . PHP_EOL . $queries . PHP_EOL . "Trace:" . PHP_EOL . $traceMsg; throw new \Exception($message, (int) $e->getCode(), $e); } throw $e; }
/** * Filters stack frames from PHPUnit classes. * * @param Exception $e * @param boolean $asString * @return string */ public static function getFilteredStacktrace(Exception $e, $asString = TRUE) { if (!defined('PHPUNIT_TESTSUITE')) { $blacklist = PHPUnit_Util_GlobalState::phpunitFiles(); } else { $blacklist = array(); } if ($asString === TRUE) { $filteredStacktrace = ''; } else { $filteredStacktrace = array(); } if ($e instanceof PHPUnit_Framework_SyntheticError) { $eTrace = $e->getSyntheticTrace(); $eFile = $e->getSyntheticFile(); $eLine = $e->getSyntheticLine(); } else { $eTrace = $e->getTrace(); $eFile = $e->getFile(); $eLine = $e->getLine(); } if (!self::frameExists($eTrace, $eFile, $eLine)) { array_unshift($eTrace, array('file' => $eFile, 'line' => $eLine)); } foreach ($eTrace as $frame) { if (isset($frame['file']) && is_file($frame['file']) && !isset($blacklist[$frame['file']])) { if ($asString === TRUE) { $filteredStacktrace .= sprintf("%s:%s\n", $frame['file'], isset($frame['line']) ? $frame['line'] : '?'); } else { $filteredStacktrace[] = $frame; } } } return $filteredStacktrace; }
public function getHtml() { $html = '<div style="padding:20px;border-radius:20px;background:#EEE;text-align:center;border:1px solid #BBB;height:50px;font-family: monospace;">'; $html .= ' <h1 style="padding:0;margin:0 0 -10px 0;font-size:20px;">Error: ' . parent::getMessage() . '</h1>'; $html .= ' <p style="font-size: smaller">In ' . parent::getFile() . ' In ' . parent::getLine() . '</p>'; $html .= '</div>'; $html .= '<br/>'; $html .= '<div style="padding: 20px 25px 30px 25px;border-radius:20px;background:#FFF;text-align:left;border:1px solid #BBB;font-family: monospace;">'; $html .= ' <h1 style="padding:0;margin:0;font-size: 20px;">Stack Trace</h1>'; $html .= ' <ul>'; foreach (parent::getTrace() as $key => $trace) { $args = []; foreach ($trace['args'] as $arg) { if (empty($args)) { $args[] = '\'\''; } else { $args[] = '\'' . $arg . '\''; } } $html .= ' <li style="list-style: none;clear: both;">'; $html .= ' <div style="float:left;margin-right: 10px;color: #9A9A9A;background-color: rgba(232, 232, 232, 0.29);width: 40px;margin-left: -40px;margin-right: 40px;text-align: right;">' . ($key + 1) . '.</div>'; $html .= ' <div style="float:left;margin-right: 10px;">' . $trace['file'] . '(' . $trace['line'] . ')</div>'; $html .= ' <div style="float:left">' . $trace['class'] . $trace['type'] . 'setPassword(' . implode(', ', $args) . ')</div>'; $html .= ' </li>'; } $html .= ' </ul>'; $html .= '</div>'; return $html; }
/** * Serialize exception object * * @param \Exception $exception * @return type */ public function exceptionToArray(\Exception $exception) { $trace = $exception->getTrace(); $className = get_class($exception); $message = $exception->getMessage() ? $exception->getMessage() : $className; return ['message' => $message, 'class' => $className, 'code' => $exception->getCode(), 'file' => $exception->getFile(), 'line' => $exception->getLine(), 'stack' => $this->stackTraceToArray($trace)]; }
/** * Constructor that called the parent \Exception constructor * * @param string $message Error message * @param int $code Error level * @param \Exception|null $previous Previous \Exception or \Error */ public function __construct(string $message, int $code = 0, $previous = null) { parent::__construct($message, $code, $previous); Ini::setIniFileName('conf.ini'); $this->logger = new Logger(Ini::getParam('Exception', 'implementedLogger')); $this->logger->log($code, $message, parent::getTrace()); }