/** * 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 \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); }
/** * Return an error into an HTTP or JSON data array. * * @param string $title * @return array */ public function error($title = null) { if ($title == null) { $title = $this->debug ? 'The application could not run because of the following error:' : 'A website error has occurred. Sorry for the temporary inconvenience.'; } $type = $this->request->getHeader('Content-Type'); $mesg = $this->exception->getMessage(); $file = $this->exception->getFile(); $line = $this->exception->getLine(); $code = $this->exception->getCode(); $statusCode = method_exists($this->exception, 'getStatusCode') ? $this->exception->getStatusCode() : null; // Check status code is null if ($statusCode == null) { $statusCode = $code >= 100 && $code <= 500 ? $code : 400; } $this->response->withStatus($statusCode); // Check logger exist if ($this->logger !== null) { // Send error to log $this->logger->addError($this->exception->getMessage()); } $this->isJson = isset($type[0]) && $type[0] == 'application/json'; // Check content-type is application/json if ($this->isJson) { // Define content-type to json $this->response->withHeader('Content-Type', 'application/json'); $error = ['status' => 'error', 'status_code' => $statusCode, 'error' => $title, 'details' => []]; // Check debug if ($this->debug) { $error['details'] = ['message' => $mesg, 'file' => $file, 'line' => $line, 'code' => $code]; } return $error; } // Define content-type to html $this->response->withHeader('Content-Type', 'text/html'); $message = sprintf('<span>%s</span>', htmlentities($mesg)); $error = ['type' => get_class($this->exception), $error['status_code'] = $statusCode, 'message' => $message]; // Check debug if ($this->debug) { $trace = $this->exception->getTraceAsString(); $trace = sprintf('<pre>%s</pre>', htmlentities($trace)); $error['file'] = $file; $error['line'] = $line; $error['code'] = $code; $error['trace'] = $trace; } $error['debug'] = $this->debug; $error['title'] = $title; return $error; }
/** * 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() */ 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 === self::CONTEXT_WEB) { $logMessage .= '. Requested URL: ' . GeneralUtility::getIndpEnv('TYPO3_REQUEST_URL'); } // Write error message to the configured syslogs GeneralUtility::sysLog($logMessage, $logTitle, GeneralUtility::SYSLOG_SEVERITY_FATAL); }
/** * @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; }
/** * Render the document * * @param boolean $cache If true, cache the output * @param array $params Associative array of attributes * * @return string The rendered data * * @since 11.1 */ public function render($cache = false, $params = array()) { // If no error object is set return null if (!isset($this->_error)) { return; } // Set the status header $status = $this->_error->getCode(); if ($status < 400 || $status > 599) { $status = 500; } JFactory::getApplication()->setHeader('status', $status . ' ' . str_replace("\n", ' ', $this->_error->getMessage())); $file = 'error.php'; // Check template $directory = isset($params['directory']) ? $params['directory'] : 'templates'; $template = isset($params['template']) ? JFilterInput::getInstance()->clean($params['template'], 'cmd') : 'system'; if (!file_exists($directory . '/' . $template . '/' . $file)) { $template = 'system'; } // Set variables $this->baseurl = JUri::base(true); $this->template = $template; $this->debug = isset($params['debug']) ? $params['debug'] : false; $this->error = $this->_error; // Load the language file for the template if able if (JFactory::$language) { $lang = JFactory::getLanguage(); // 1.5 or core then 1.6 $lang->load('tpl_' . $template, JPATH_BASE, null, false, true) || $lang->load('tpl_' . $template, $directory . '/' . $template, null, false, true); } // Load $data = $this->_loadTemplate($directory . '/' . $template, $file); parent::render(); return $data; }
/** * @inheritDoc */ public function __construct(\Throwable $t) { $this->message = $t->getMessage(); $this->code = $t->getCode(); $this->file = $t->getFile(); $this->line = $t->getLine(); }
/** * 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); }
/** * @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')); } }
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()); }
/** * 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(); }
/** * 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()); } }
/** * 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 $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); }
/** * Creates html error message */ private function createErrorHtml(bool $dismissable = false) { $html = ' <div class="alert alert-danger' . ($dismissable == true ? ' alert-dismissible' : '') . '" role="alert" id="core-error-' . $this->throwable->getCode() . '">'; if ($dismissable) { $html .= '<button type="button" class="close" data-dismiss="alert"><span aria-hidden="true">×</span><span class="sr-only">Close</span></button>'; } switch (true) { case $this->public: $html .= $this->getHeadline(); $html .= $this->getMessage(); $html .= $this->getFileinfo(); $html .= $this->getTrace(); break; default: $html .= ' <h3 class="no-top-margin">Error</h3> <p>Sorry for that! Webmaster has been informed. Please try again later.</p>'; } $html .= ' </div>'; return $html; }
/** * 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 $xw = new \XMLWriter(); $xw->openMemory(); $xw->setIndent(true); $xw->setIndentString("\t"); $xw->startDocument('1.0', 'UTF-8'); $xw->startElement('error'); $xw->writeElement('code', $error->getCode()); $xw->writeElement('message', $error->getMessage()); // Include the stack trace if in debug mode if (JDEBUG) { $xw->writeElement('trace', $error->getTraceAsString()); } // End error element $xw->endElement(); // Push the data object into the document $this->getDocument()->setBuffer($xw->outputMemory(true)); if (ob_get_contents()) { ob_end_clean(); } return $this->getDocument()->render(); }
/** * Convert an Exception or Error into an array (for logging) * * @param \Throwable $ex * @return array */ function throwableToArray(\Throwable $ex) : array { $prev = $ex->getPrevious(); return ['line' => $ex->getLine(), 'file' => $ex->getFile(), 'message' => $ex->getMessage(), 'code' => $ex->getCode(), 'trace' => $ex->getTrace(), 'previous' => $prev ? throwableToArray($prev) : null]; }
/** * Prepare a response in case an error occurred. * * @param \Throwable $exception * @param Http\Response $response * @return void */ protected function prepareErrorResponse($exception, Http\Response $response) { $pathPosition = strpos($exception->getFile(), 'Packages/'); $filePathAndName = $pathPosition !== false ? substr($exception->getFile(), $pathPosition) : $exception->getFile(); $exceptionCodeNumber = $exception->getCode() > 0 ? '#' . $exception->getCode() . ': ' : ''; $content = PHP_EOL . 'Uncaught Exception in Flow ' . $exceptionCodeNumber . $exception->getMessage() . PHP_EOL; $content .= 'thrown in file ' . $filePathAndName . PHP_EOL; $content .= 'in line ' . $exception->getLine() . PHP_EOL . PHP_EOL; $content .= Debugger::getBacktraceCode($exception->getTrace(), false, true) . PHP_EOL; if ($exception instanceof Exception) { $statusCode = $exception->getStatusCode(); } else { $statusCode = 500; } $response->setStatus($statusCode); $response->setContent($content); $response->setHeader('X-Flow-ExceptionCode', $exception->getCode()); $response->setHeader('X-Flow-ExceptionMessage', $exception->getMessage()); }
/** * @param Throwable $ex The Exception / Error being handled */ function akeeba_exception_handler($ex) { echo "\n\n"; echo "********** ERROR! **********\n\n"; echo $ex->getMessage(); echo "\n\nTechnical information:\n\n"; echo "Code: " . $ex->getCode() . "\n"; echo "File: " . $ex->getFile() . "\n"; echo "Line: " . $ex->getLine() . "\n"; echo "\nStack Trace:\n\n" . $ex->getTraceAsString(); die("\n\n"); }
/** * Formats and echoes the exception for the command line * * @param \Throwable $exception The throwable object. * @return void */ public function echoExceptionCLI(\Throwable $exception) { $filePathAndName = $exception->getFile(); $exceptionCodeNumber = $exception->getCode() > 0 ? '#' . $exception->getCode() . ': ' : ''; $this->writeLogEntries($exception, self::CONTEXT_CLI); echo LF . 'Uncaught TYPO3 Exception ' . $exceptionCodeNumber . $exception->getMessage() . LF; echo 'thrown in file ' . $filePathAndName . LF; echo 'in line ' . $exception->getLine() . LF . LF; die(1); }
private function checkForTypeLoaderThrowable(\Throwable $throwable) { if (null !== ($tle = TypeLoader::getLatestException())) { TypeLoader::clear(); if ($throwable instanceof \Error && ($throwable->getCode() === 0 || $throwable->getCode() === E_ERROR) && $throwable->getFile() === $tle->getFile() && $throwable->getLine() === $tle->getLine()) { return $tle; } } return $throwable; }
/** * Internal processor for all error handlers * * @param Exception|Throwable $error The Exception or Throwable object to be handled. * * @return void * * @since 3.5 */ private static function doErrorHandling($error) { $app = JFactory::getApplication(); if ($app->isAdmin() || (int) $error->getCode() !== 404) { // Proxy to the previous exception handler if available, otherwise just render the error page if (self::$previousExceptionHandler) { call_user_func_array(self::$previousExceptionHandler, array($error)); } else { JErrorPage::render($error); } } $uri = JUri::getInstance(); $url = rawurldecode($uri->toString(array('scheme', 'host', 'port', 'path', 'query', 'fragment'))); $urlRel = rawurldecode($uri->toString(array('path', 'query', 'fragment'))); $urlWithoutQuery = rawurldecode($uri->toString(array('scheme', 'host', 'port', 'path', 'fragment'))); $urlRelWithoutQuery = rawurldecode($uri->toString(array('path', 'fragment'))); // Why is this (still) here? if (strpos($url, 'mosConfig_') !== false || strpos($url, '=http://') !== false) { JErrorPage::render($error); } $db = JFactory::getDbo(); $query = $db->getQuery(true); $query->select('*')->from($db->quoteName('#__redirect_links'))->where('(' . $db->quoteName('old_url') . ' = ' . $db->quote($url) . ' OR ' . $db->quoteName('old_url') . ' = ' . $db->quote($urlRel) . ' OR ' . $db->quoteName('old_url') . ' = ' . $db->quote($urlWithoutQuery) . ' OR ' . $db->quoteName('old_url') . ' = ' . $db->quote($urlRelWithoutQuery) . ')'); $db->setQuery($query); $redirect = null; try { $redirects = $db->loadAssocList(); } catch (Exception $e) { JErrorPage::render(new Exception(JText::_('PLG_SYSTEM_REDIRECT_ERROR_UPDATING_DATABASE'), 500, $e)); } $possibleMatches = array_unique(array($url, $urlRel, $urlWithoutQuery, $urlRelWithoutQuery)); foreach ($possibleMatches as $match) { if (($index = array_search($match, array_column($redirects, 'old_url'))) !== false) { $redirect = (object) $redirects[$index]; if ((int) $redirect->published === 1) { break; } } } // A redirect object was found and, if published, will be used if (!is_null($redirect) && (int) $redirect->published === 1) { if (!$redirect->header || (bool) JComponentHelper::getParams('com_redirect')->get('mode', false) === false) { $redirect->header = 301; } if ($redirect->header < 400 && $redirect->header >= 300) { $urlQuery = $uri->getQuery(); $oldUrlParts = parse_url($redirect->old_url); if (empty($oldUrlParts['query']) && $urlQuery !== '') { $redirect->new_url .= '?' . $urlQuery; } $destination = JUri::isInternal($redirect->new_url) ? JRoute::_($redirect->new_url) : $redirect->new_url; $app->redirect($destination, (int) $redirect->header); } JErrorPage::render(new RuntimeException($error->getMessage(), $redirect->header, $error)); } elseif (is_null($redirect)) { $params = new Registry(JPluginHelper::getPlugin('system', 'redirect')->params); if ((bool) $params->get('collect_urls', true)) { $data = (object) array('id' => 0, 'old_url' => $url, 'referer' => $app->input->server->getString('HTTP_REFERER', ''), 'hits' => 1, 'published' => 0, 'created_date' => JFactory::getDate()->toSql()); try { $db->insertObject('#__redirect_links', $data, 'id'); } catch (Exception $e) { JErrorPage::render(new Exception(JText::_('PLG_SYSTEM_REDIRECT_ERROR_UPDATING_DATABASE'), 500, $e)); } } } else { $redirect->hits += 1; try { $db->updateObject('#__redirect_links', $redirect, 'id'); } catch (Exception $e) { JErrorPage::render(new Exception(JText::_('PLG_SYSTEM_REDIRECT_ERROR_UPDATING_DATABASE'), 500, $e)); } } JErrorPage::render($error); }
public function logException(\Throwable $e, $trace = null) { if ($trace === null) { $trace = $e->getTrace(); } $errstr = $e->getMessage(); $errfile = $e->getFile(); $errno = $e->getCode(); $errline = $e->getLine(); $errorConversion = [0 => "EXCEPTION", E_ERROR => "E_ERROR", E_WARNING => "E_WARNING", E_PARSE => "E_PARSE", E_NOTICE => "E_NOTICE", E_CORE_ERROR => "E_CORE_ERROR", E_CORE_WARNING => "E_CORE_WARNING", E_COMPILE_ERROR => "E_COMPILE_ERROR", E_COMPILE_WARNING => "E_COMPILE_WARNING", E_USER_ERROR => "E_USER_ERROR", E_USER_WARNING => "E_USER_WARNING", E_USER_NOTICE => "E_USER_NOTICE", E_STRICT => "E_STRICT", E_RECOVERABLE_ERROR => "E_RECOVERABLE_ERROR", E_DEPRECATED => "E_DEPRECATED", E_USER_DEPRECATED => "E_USER_DEPRECATED"]; if ($errno === 0) { $type = LogLevel::CRITICAL; } else { $type = ($errno === E_ERROR or $errno === E_USER_ERROR) ? LogLevel::ERROR : (($errno === E_USER_WARNING or $errno === E_WARNING) ? LogLevel::WARNING : LogLevel::NOTICE); } $errno = isset($errorConversion[$errno]) ? $errorConversion[$errno] : $errno; if (($pos = strpos($errstr, "\n")) !== false) { $errstr = substr($errstr, 0, $pos); } $errfile = \pocketmine\cleanPath($errfile); $this->log($type, get_class($e) . ": \"{$errstr}\" ({$errno}) in \"{$errfile}\" at line {$errline}"); foreach (@\pocketmine\getTrace(1, $trace) as $i => $line) { $this->debug($line); } }
/** * @param \Throwable $exception */ public static function log(\Throwable $exception) { $level = 'emergency'; if ($exception instanceof Error) { foreach (self::LEVEL_LOG as $log => $codes) { if (in_array($exception->getCode(), $codes) === true) { $level = $log; } } } $context = []; $reflection = new \ReflectionClass($exception); foreach ($reflection->getProperties() as $property) { if (!$property->isPrivate()) { $property->setAccessible(true); $value = $property->getValue($exception); // can be exported as context if ($value === null || is_scalar($value) || is_callable([$value, '__toString'])) { $context[$property->getName()] = (string) $value; } } } unset($context['message']); $start = self::request()->getServer('REQUEST_TIME_FLOAT'); $end = microtime(true); $context['Duration'] = round(($end - $start) * 1000, 3); $context['Ip'] = Ip::get(); $context['Url'] = self::request()->getUri()->get(false); $context['Trace'] = $exception->getTraceAsString(); $context['Referer'] = self::request()->getHeader('Referer'); self::logger()->log($level, $exception->getMessage(), $context); }
/** * Log the Exception / Error thrown * * @param \Throwable $t The Exception / Error thrown */ public function log(\Throwable $t) { $this->logger->log($t->getCode(), $t->getMessage(), $t->getTrace()); }
/** * Create error response from exception * @param \Exception|\Throwable $e * @return \Drahak\Restful\IResource */ protected function createErrorResource($e) { if ($e instanceof \Exception || $e instanceof \Throwable) { $resource = $this->resourceFactory->create(array('code' => $e->getCode(), 'status' => 'error', 'message' => $e->getMessage())); } else { $resource = $this->resourceFactory->create(array('code' => 500, 'status' => 'error', 'message' => (string) $e)); } if (isset($e->errors) && $e->errors) { $resource->errors = $e->errors; } return $resource; }
/** * Method run by PHP's exception handler * @param \Throwable $e */ public function exceptionHandler(\Throwable $e) { if ($e instanceof \Error) { $this($e->getCode(), $e->getMessage(), $e->getFile(), $e->getLine()); if ($this->rethrowException) { goto rethrow; } } rethrow: throw $e; }
/** * Send a close frame to the client. * * @param BufferedDuplexStreamInterface $socket * @param \Throwable $e */ protected function sendCloseFrame(BufferedDuplexStreamInterface $socket, \Throwable $e = NULL) : \Generator { if ($socket->eof()) { return; } $code = isset($e) ? Frame::CODE_NORMAL_CLOSURE : Frame::CODE_UNEXPECTED_CONDITION; $err = ''; if ($e instanceof WebSocketException) { $code = $e->getCode() ?: Frame::CODE_UNEXPECTED_CONDITION; $err = $e->getMessage(); } yield from $socket->write((new Frame(Frame::CONNECTION_CLOSE, pack('n', $code) . $err))->encode(), 10000); }
/** * On application error * @param Application $application * @param \Exception|\Throwable $e */ public function error(Application $application, $e) { if ($e instanceof NetteBadRequestException && $e->getCode() === 404) { $this->checkAllowedMethods(); } }