/** * @param \Exception|\Throwable $e * @return array|null */ public static function renderException($e = NULL) { if (!$e instanceof Kdyby\Autowired\Exception || !$e->getReflector()) { return NULL; } return ['tab' => 'Autowired', 'panel' => self::highlightException($e)]; }
/** * @param \Throwable $exception * * @return bool */ public function exceptionHandler(\Throwable $exception) { if ($exception instanceof ResponseCode) { try { $out = $this->render($exception->getCode(), [], $exception->display()); } catch (\Throwable $exception) { return $this->exceptionHandler($exception); } // debug on dev / display trace if (!(AbstractApp::env() != AbstractApp::PRODUCTION && ob_get_length() > 0)) { self::response()->addHeader('Content-Type', $this->getErrorContentType()); } self::response()->setStatus($exception->getCode()); self::response()->setBody($out); HttpApp::instance()->end(); } else { Handler::log($exception); if (AbstractApp::env() != AbstractApp::PRODUCTION) { Handler::exceptionHandler($exception); } else { $throw = new ResponseCode($exception->getMessage(), 500, $exception); $this->exceptionHandler($throw); } } return true; }
public function throwabeExtensions() { $t = new Throwable('Test'); $this->assertNotEquals(array(), $t->getStackTrace()); $t->clearStackTrace(); $this->assertEquals(array(), $t->getStackTrace()); }
public function friendlyExceptionHandler(\Throwable $exception) { $message = $exception->getMessage(); $file = $exception->getFile(); $line = $exception->getLine(); // $obLevel = ob_get_level(); if ($obLevel > 0) { ob_end_clean(); } if (self::$_isActive) { echo $message; return; } self::$_isActive = true; // Log Messages error_log("Exception: " . $message . " in {$file} on line {$line}"); $html = '<html lang="' . $this->_htmlLang . '"><head><meta charset="UTF-8"><title>' . $this->_escapeString($message) . '</title></head><body>'; $html .= '<table width="100%" height="100%"><tr><td><table width="50%" border="0" align="center" cellpadding="4" cellspacing="1" bgcolor="#cccccc">'; $html .= '<tr bgcolor="#dddddd"><td height="40">' . $this->_tableTitle . '</td></tr><tr bgcolor="#ffffff"><td height="150" align="center">'; $html .= $this->_escapeString($message); $html .= '</td></tr><tr bgcolor="#f2f2f2"><td height="40" align="center"><a href="/">' . $this->_backText . '</a></td></tr></table>'; $html .= '</td></tr><tr><td height="35%"></td></tr></table></body></html>'; echo $html; self::$_isActive = false; // return true; }
/** * @inheritDoc */ public function __construct(\Throwable $t) { $this->message = $t->getMessage(); $this->code = $t->getCode(); $this->file = $t->getFile(); $this->line = $t->getLine(); }
/** * May be set as exception handler, i.e. set_exception_handler('alkemann\h2l\handleError'); * * @param \Throwable $e */ function handleError(\Throwable $e) { if ($e instanceof \alkemann\h2l\exceptions\InvalidUrl) { Log::info("InvalidUrl: " . $e->getMessage()); echo (new Error(404, $e->getMessage()))->render(); return; } if ($e instanceof \Exception) { Log::error(get_class($e) . ": " . $e->getMessage()); } elseif ($e instanceof \Error) { Log::alert(get_class($e) . ": " . $e->getMessage()); } if (DEBUG && isset($e->xdebug_message)) { header("Content-type: text/html"); echo '<table>' . $e->xdebug_message . '</table><br>'; dbp('xdebug_message'); d($e); } elseif (DEBUG) { header("Content-type: text/html"); echo '<h1>' . $e->getMessage() . '</h1>'; d($e); } else { (new Error(500, $e->getMessage()))->render(); } }
/** * Throwable handler. * * @since 160711 Throwables. * * @param \Throwable $Throwable Error/Exception. */ public function handler(\Throwable $Throwable) { if ($this->c::isCli()) { // Set `STDERR` so that it can be used in CLI feedback. // If debugging, `STDERR` should include a full stack trace. // If it's not an interactive terminal session, try to log the error. // The exit status should always be `1` to indicate an error. try { // Catch throwables. $this->c::noCacheFlags(); $this->c::sessionWriteClose(); $this->c::obEndCleanAll(); if ($this->App->Config->©debug['©enable']) { $this->c::writeStderr($Throwable->__toString()); } else { $this->c::writeStderr($Throwable->getMessage()); } if (!$this->c::isCliInteractive()) { error_log(str_replace("", '', $Throwable->__toString())); } exit(1); // Exit status code. // } catch (\Throwable $inner_Throwable) { // Edge case. exit(1); // Simply exit in this edge case. } } elseif (!headers_sent()) { // Send a 500 error response code. // If there is a throwable template, use the throwable template. // In either case, rethrow; i.e., allow PHP to log as an error. // It's also IMPORTANT to rethrow so that execution stops! try { // Catch throwables. $this->c::noCacheFlags(); $this->c::sessionWriteClose(); $this->c::obEndCleanAll(); $this->c::statusHeader(500); $this->c::noCacheHeaders(); header('content-type: text/html; charset=utf-8'); echo $this->c::getTemplate('http/html/status/500.php')->parse(['Throwable' => $Throwable]); // } catch (\Throwable $inner_Throwable) { echo 'Unexpected error. Please try again.' . "\n"; // Edge case. } throw $Throwable; // Rethrow. i.e., allow PHP to log as an error. // ↑ NOTE: Assumes throwables will not be handled here when `display_errors=yes`. // Therefore, when the above template is displayed, that's all you'll see in most cases. // i.e., Under most conditions, the display of this PHP error should not be seen. Only logged. } else { // Should be avoided. It's always better to buffer output so that an error // can be shown instead of what would have been output to a browser otherwise. // Our own template handler uses output buffering so this is not an issue with core. throw $Throwable; // Rethrow. i.e., log and/or display if debugging. } }
/** * Display the given exception to the user. * * @param \Exception $exception * @return \Symfony\Component\HttpFoundation\Response */ public function display(\Throwable $exception) { if ($this->returnJson) { return new JsonResponse(array('error' => $exception->getMessage(), 'file' => $exception->getFile(), 'line' => $exception->getLine()), 500); } return $this->symfony->createResponse($exception); }
/** * @param \Throwable $e */ public function handleException(\Throwable $e) { $code = $e->getCode() >= 400 ? $e->getCode() : 500; $exceptionData = ['error' => ['code' => $e->getCode(), 'message' => $e->getMessage()]]; http_response_code($code); echo json_encode($exceptionData, JSON_PRETTY_PRINT); exit(1); }
/** * Render the error page based on an exception. * * @param Exception|Throwable $error An Exception or Throwable (PHP 7+) object for which to render the error page. * * @return void * * @since 3.0 */ public static function render($error) { $expectedClass = PHP_MAJOR_VERSION >= 7 ? 'Throwable' : 'Exception'; $isException = $error instanceof $expectedClass; // In PHP 5, the $error object should be an instance of Exception; PHP 7 should be a Throwable implementation if ($isException) { try { // If site is offline and it's a 404 error, just go to index (to see offline message, instead of 404) if ($error->getCode() == '404' && JFactory::getConfig()->get('offline') == 1) { JFactory::getApplication()->redirect('index.php'); } $app = JFactory::getApplication(); $document = JDocument::getInstance('error'); if (!$document) { // We're probably in an CLI environment jexit($error->getMessage()); } // Get the current template from the application $template = $app->getTemplate(); // Push the error object into the document $document->setError($error); if (ob_get_contents()) { ob_end_clean(); } $document->setTitle(JText::_('Error') . ': ' . $error->getCode()); $data = $document->render(false, array('template' => $template, 'directory' => JPATH_THEMES, 'debug' => JDEBUG)); // Do not allow cache $app->allowCache(false); // If nothing was rendered, just use the message from the Exception if (empty($data)) { $data = $error->getMessage(); } $app->setBody($data); echo $app->toString(); $app->close(0); // This return is needed to ensure the test suite does not trigger the non-Exception handling below return; } catch (Throwable $e) { // Pass the error down } catch (Exception $e) { // Pass the error down } } // This isn't an Exception, we can't handle it. if (!headers_sent()) { header('HTTP/1.1 500 Internal Server Error'); } $message = 'Error displaying the error page'; if ($isException) { $message .= ': '; if (isset($e)) { $message .= $e->getMessage() . ': '; } $message .= $error->getMessage(); } echo $message; jexit(1); }
/** * Handles exception error message logging if logging is enabled then re-throws the exception. * * @param LogOperation|null $log * @param \Throwable|\Exception $exception * @throws \LdapTools\Exception\LdapConnectionException * @throws null */ protected function logExceptionAndThrow($exception, LogOperation $log = null) { if ($this->shouldLog($log) && is_null($log->getStartTime())) { $this->logStart($log); } if ($this->shouldLog($log)) { $log->setError($exception->getMessage()); } throw $exception; }
/** * @dataProvider providerTestPrepareStep * @param HtmlHelper $helper * @param \Exception|\Throwable $exception */ public function testPrepareStep(HtmlHelper $helper, $exception) { foreach ($exception->getTrace() as $step) { $colorized = $helper->prepareStep($step); $this->assertTrue(is_array($colorized)); foreach (array('title', 'source', 'key', 'arguments') as $key) { $this->assertTrue(isset($colorized[$key])); } $this->assertTrue(is_array($colorized['arguments'])); } }
/** * @param \Throwable $exception */ public static function exceptionHandler(\Throwable $exception) { // This error code is not included in error_reporting if (!error_reporting() || $exception->getLine() == 0) { return; } $output = new ConsoleOutput(OutputInterface::VERBOSITY_VERY_VERBOSE); if (!$exception instanceof \Exception) { $exception = new \ErrorException($exception->getMessage(), $exception->getCode(), 0, $exception->getFile(), $exception->getLine(), $exception); self::$application->renderException($exception, $output); } else { self::$application->renderException($exception, $output); } }
/** * Render the error page for the given object * * @param \Throwable|\Exception $error The error object to be rendered * * @return string * * @since 4.0 */ protected function doRender($error) { // Create our data object to be rendered $data = ['error' => true, 'code' => $error->getCode(), 'message' => $error->getMessage()]; // Include the stack trace if in debug mode if (JDEBUG) { $data['trace'] = $error->getTraceAsString(); } // Push the data object into the document $this->getDocument()->setBuffer(json_encode($data)); if (ob_get_contents()) { ob_end_clean(); } return $this->getDocument()->render(); }
/** * 记录起始请求日志 * 记录成功返回true,失败或没记录日志返回false * * @param \Exception|\Throwable $ex * @return bool */ public static function error_log($ex) { if (!BaseLog::isLog('error')) { return false; } if (!Config::getEnv("app.framework_error_log")) { return false; } $data = Request::nonPostParam(); if (Config::getEnv("app.request_log_post")) { $data = Request::param(); } $log_msg = "\r\nQP->Main最外层捕捉到Exception异常:\r\n请求参数:{Param}\r\n异常信息:{E_Msg}\r\n异常位置:{E_Point}\r\n更多异常队列信息:{E_Trace}\r\n"; $log_data = ['Param' => json_encode($data), 'E_Msg' => $ex->getMessage(), 'E_Point' => $ex->getFile() . ":" . $ex->getLine(), 'E_Trace' => json_encode($ex->getTrace())]; return Log::error($log_msg, $log_data, true, 'framework'); }
/** * display system error page as result of an error or exception * * @param Throwable $e * @return Response */ private static function render($e) { if ($e->getCode() === 400) { return (new ErrorsController())->error(400); } return (new ErrorsController())->error(500); }
/** * Send exception message to client * @param \Exception $exception */ public function dispatchException(\Throwable $exception) { if ($this->isActive()) { if ($this->dispatchPreviousExceptions && $exception->getPrevious()) { $this->dispatchException($exception->getPrevious()); } $message = new \PhpConsole\ErrorMessage(); $message->code = $exception->getCode(); $message->class = get_class($exception); $message->data = $this->dumper->dump($exception->getMessage()); $message->file = $exception->getFile(); $message->line = $exception->getLine(); $message->trace = self::fetchTrace($exception->getTrace(), $message->file, $message->line); $this->sendMessage($message); } }
/** * @param Throwable|Exception $e */ public function __construct($e) { // PDOException::getCode() is a string. // @see http://php.net/manual/en/class.pdoexception.php#95812 parent::__construct($e->getMessage(), (int) $e->getCode()); $this->classname = get_class($e); $this->file = $e->getFile(); $this->line = $e->getLine(); $this->serializableTrace = $e->getTrace(); foreach ($this->serializableTrace as $i => $call) { unset($this->serializableTrace[$i]['args']); } if ($e->getPrevious()) { $this->previous = new self($e->getPrevious()); } }
/** * Return Error throwable trace in array format. * * @param \Error|\Exception $ex * @return string[] */ public static function toThrowableTrace($ex) { $list = []; for ($stack = Throwable::getThrowableStack($ex); $stack !== null; $stack = $stack['prev']) { $list[] = Throwable::parseThrowableMessage($stack); } return array_reverse($list); }
/** * Writes exception to different logs * * @param \Exception|\Throwable $exception The exception(PHP 5.x) or throwable(PHP >= 7.0) object. * @param string $context The context where the exception was thrown, WEB or CLI * @return void * @see \TYPO3\CMS\Core\Utility\GeneralUtility::sysLog(), \TYPO3\CMS\Core\Utility\GeneralUtility::devLog() * @TODO #72293 This will change to \Throwable only if we are >= PHP7.0 only */ protected function writeLogEntries($exception, $context) { // Do not write any logs for this message to avoid filling up tables or files with illegal requests if ($exception->getCode() === 1396795884) { return; } $filePathAndName = $exception->getFile(); $exceptionCodeNumber = $exception->getCode() > 0 ? '#' . $exception->getCode() . ': ' : ''; $logTitle = 'Core: Exception handler (' . $context . ')'; $logMessage = 'Uncaught TYPO3 Exception: ' . $exceptionCodeNumber . $exception->getMessage() . ' | ' . get_class($exception) . ' thrown in file ' . $filePathAndName . ' in line ' . $exception->getLine(); if ($context === 'WEB') { $logMessage .= '. Requested URL: ' . GeneralUtility::getIndpEnv('TYPO3_REQUEST_URL'); } $backtrace = $exception->getTrace(); // Write error message to the configured syslogs GeneralUtility::sysLog($logMessage, $logTitle, GeneralUtility::SYSLOG_SEVERITY_FATAL); // When database credentials are wrong, the exception is probably // caused by this. Therefor we cannot do any database operation, // otherwise this will lead into recurring exceptions. try { // Write error message to devlog // see: $TYPO3_CONF_VARS['SYS']['enable_exceptionDLOG'] if (TYPO3_EXCEPTION_DLOG) { GeneralUtility::devLog($logMessage, $logTitle, 3, array('TYPO3_MODE' => TYPO3_MODE, 'backtrace' => $backtrace)); } // Write error message to sys_log table $this->writeLog($logTitle . ': ' . $logMessage); } catch (\Exception $exception) { } }
/** * @param \Exception|\Throwable $exception * @param \Spryker\Shared\EventJournal\Model\EventJournalInterface $eventJournal * @param \Spryker\Shared\NewRelic\ApiInterface $newRelicApi * @param bool $ignoreInternalExceptions * * @return void */ protected static function sendExceptionToEventJournal($exception, EventJournalInterface $eventJournal, ApiInterface $newRelicApi, $ignoreInternalExceptions = false) { try { $event = new Event(); $event->setField('message', $exception->getMessage()); $event->setField('trace', $exception->getTraceAsString()); $event->setField('class_name', get_class($exception)); $event->setField('file_name', $exception->getFile()); $event->setField('line', $exception->getLine()); $event->setField(Event::FIELD_NAME, 'exception'); self::addDeploymentInformation($event); $eventJournal->saveEvent($event); } catch (\Exception $internalException) { if (!$ignoreInternalExceptions) { self::sendExceptionToNewRelic($internalException, $eventJournal, $newRelicApi, true); } } }
/** * @param \Exception|\Throwable $exception */ public function handle_exception($exception) { if (getenv('APP_ENV') === 'dev') { list($code, $file, $line, $message, $previous, $trace, $trace_string) = [$exception->getCode(), $exception->getFile(), $exception->getLine(), $exception->getMessage(), $exception->getPrevious(), $exception->getTrace(), $exception->getTraceAsString()]; $trace_info = "<b>file</b>: {$trace[0]['file']} <b>in line</b> ({$trace[0]['line']})"; echo "<h2>COGS Runtime Exception: [::{$code}] {$message}</h2>"; echo "<b>Trace:</b><br>"; echo "<pre>{$trace_string}</pre>"; echo "<b>Debug:</b><br>"; dump(compact('code', 'file', 'line', 'message', 'previous', 'trace')); } }
/** * Determines, whether Exception details should be outputted * * @param \Throwable $exception The throwable object. * @return bool */ protected function discloseExceptionInformation(\Throwable $exception) { // Allow message to be shown in production mode if the exception is about // trusted host configuration. By doing so we do not disclose // any valuable information to an attacker but avoid confusions among TYPO3 admins // in production context. if ($exception->getCode() === 1396795884) { return true; } // Show client error messages 40x in every case if ($exception instanceof Http\AbstractClientErrorException) { return true; } // Only show errors in FE, if a BE user is authenticated if (TYPO3_MODE === 'FE') { return $GLOBALS['TSFE']->beUserLogin; } return true; }
/** * @param Throwable $exception */ public function handle(\Throwable $exception) { if ($exception instanceof HttpException) { http_response_code($exception->getStatusCode()); } if (false === $this->debug) { return; } if (null !== $exception->getPrevious()) { $exception = $exception->getPrevious(); } $message = $exception->getMessage(); $trace = $exception->getTrace(); array_unshift($trace, array('function' => '', 'file' => $exception->getFile() != null ? $exception->getFile() : null, 'line' => $exception->getLine() != null ? $exception->getLine() : null, 'args' => array())); $firstTrace = array_shift($trace); $firstTrace['excerpt'] = $this->excerpt($firstTrace['file'], $firstTrace['line']); array_unshift($trace, $firstTrace); echo $this->templateEngine->render(__DIR__ . '/templates/exception.php', array('message' => $message, 'trace' => $trace)); }
/** * @param Exception|\Throwable $ex */ private static function getErrorResponse($ex) { $debugTrace = $ex->getTraceAsString(); $message = $ex->getMessage(); $isHtmlMessage = method_exists($ex, 'isHtmlMessage') && $ex->isHtmlMessage(); if (!$isHtmlMessage && Request::isApiRequest($_GET)) { $outputFormat = strtolower(Common::getRequestVar('format', 'xml', 'string', $_GET + $_POST)); $response = new ResponseBuilder($outputFormat); return $response->getResponseException($ex); } elseif (!$isHtmlMessage) { $message = Common::sanitizeInputValue($message); } $logo = new CustomLogo(); $logoHeaderUrl = false; $logoFaviconUrl = false; try { $logoHeaderUrl = $logo->getHeaderLogoUrl(); $logoFaviconUrl = $logo->getPathUserFavicon(); } catch (Exception $ex) { try { Log::debug($ex); } catch (\Exception $otherEx) { // DI container may not be setup at this point } } $result = Piwik_GetErrorMessagePage($message, $debugTrace, true, true, $logoHeaderUrl, $logoFaviconUrl); try { /** * Triggered before a Piwik error page is displayed to the user. * * This event can be used to modify the content of the error page that is displayed when * an exception is caught. * * @param string &$result The HTML of the error page. * @param Exception $ex The Exception displayed in the error page. */ Piwik::postEvent('FrontController.modifyErrorPage', array(&$result, $ex)); } catch (ContainerDoesNotExistException $ex) { // this can happen when an error occurs before the Piwik environment is created } return $result; }
/** * Handle uncaught exception and throwables for the system by logging information and displaying a generic notice * to the user so that they are informed of an error without exposing information that could be used for an attack. * * @param \Throwable $uncaught A throwable that was not caught in the system. * * @SuppressWarnings(PHPMD.CamelCaseVariableName) * @SuppressWarnings(PHPMD.Superglobals) */ public function handler(\Throwable $uncaught) { trigger_error($uncaught->getMessage(), E_USER_WARNING); $currentBuffer = (string) $this->writer; if (!empty($currentBuffer)) { trigger_error('Buffer needs to be flushed in exception handler for clean error page. Buffer was: ' . $currentBuffer, E_USER_WARNING); $this->writer->flush(); } $this->writer->writeStart(); $this->writer->write(['head', [], [['title', [], ['Internal Error']]]]); if (isset($this->viewThrowable)) { $this->viewThrowable->set($uncaught); $this->writer->write(['body', [], [['h1', [], 'Internal Error'], $this->viewThrowable->get()]]); } else { $this->writer->write(['body', [], [['h1', [], 'Internal Error'], ['p', [], 'We are sorry about this error, the administrator has been notified and we will fix this issue as soon as possible. Please contact us for more information.']]]); } $this->writer->writeEnd(); $this->response->setStatus(500); $this->response->setBody((string) $this->writer); $this->response->send(); }
/** * QP框架异常处理方式 * * @param \Exception|\Throwable $ex */ public function fatalHandler($ex) { if (Config::getEnv("app.debug")) { echo "<pre>"; echo "Exception : ", $ex->getMessage(), "<br>"; echo "Catch position : " . $ex->getFile() . " : " . $ex->getLine() . "<br><br>"; echo $ex->getTraceAsString(); } else { echo strval(Config::getEnv("app.prod_tip")); } exit; }
public function __construct(\Throwable $e) { if ($e instanceof \ParseError) { $message = 'Parse error: ' . $e->getMessage(); $severity = E_PARSE; } elseif ($e instanceof \TypeError) { $message = 'Type error: ' . $e->getMessage(); $severity = E_RECOVERABLE_ERROR; } else { $message = $e->getMessage(); $severity = E_ERROR; } \ErrorException::__construct($message, $e->getCode(), $severity, $e->getFile(), $e->getLine()); $this->setTrace($e->getTrace()); }
/** * @param \Throwable $t * @throws \Comely\Framework\KernelException * @throws \Comely\KnitException */ public function send(\Throwable $t) { $knit = (new Knit())->setTemplatePath(__DIR__)->setCompilerPath($this->kernel->getDisk("cache")); // Extract information from \Throwable $error = ["message" => null, "method" => null, "code" => $t->getCode(), "file" => $t->getFile(), "line" => $t->getLine(), "trace" => []]; // Check if exception has "getTranslated" method $error["message"] = method_exists($t, "getTranslated") ? $t->getTranslated() : $t->getMessage(); // Check if exception is child of ComelyException if (method_exists($t, "getMethod") && is_subclass_of($t, "ComelyException")) { $error["method"] = $t->getMethod(); $error["source"] = "Component"; } else { $error["method"] = get_class($t); $error["source"] = "Caught"; } // Populate Trace foreach ($t->getTrace() as $trace) { if (Arrays::hasKeys($trace, ["function", "file", "line"])) { $trace["method"] = $trace["function"]; if (isset($trace["class"])) { $trace["method"] = $trace["class"] . $trace["type"] . $trace["function"]; } $error["trace"][] = $trace; } } // Config $config = $this->kernel->config()->getNode("app"); $display = ["backtrace" => $config["errorHandler"]["screen"]["debugBacktrace"] ?? false, "triggered" => $config["errorHandler"]["screen"]["triggeredErrors"] ?? false, "paths" => $config["errorHandler"]["screen"]["completePaths"] ?? false]; // Assign values $knit->assign("display", $display); $knit->assign("error", $error); $knit->assign("triggered", $this->kernel->errorHandler()->fetchAll()); $knit->assign("version", ["comely" => \Comely::VERSION, "kernel" => Kernel::VERSION, "framework" => Kernel::VERSION, "knit" => Knit::VERSION]); // Prepare template $screen = $knit->prepare("screen.knit"); $screen = str_replace("%%knit-timer%%", number_format($screen->getTimer(), 6, ".", ""), $screen->getOutput()); exit($screen); }
/** * Shorthand: Logs the given Exception. * * @param Throwable|Exception $exception The Exception to log */ public static function logException($exception) { if ($exception instanceof ErrorException) { self::logError($exception->getSeverity(), $exception->getMessage(), $exception->getFile(), $exception->getLine()); } else { $logger = self::factory(); $logger->log(get_class($exception), $exception->getMessage(), [], $exception->getFile(), $exception->getLine()); } }