Example #1
0
/**
 * 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();
    }
}
Example #2
0
 /**
  * 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;
 }
 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());
 }
Example #4
0
 /**
  * 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;
 }
Example #5
0
 /**
  * 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);
 }
 /**
  * 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) {
     }
 }
 /**
  * @inheritDoc
  */
 public function __construct(\Throwable $t)
 {
     $this->message = $t->getMessage();
     $this->code = $t->getCode();
     $this->file = $t->getFile();
     $this->line = $t->getLine();
 }
Example #9
0
 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;
 }
Example #10
0
 /**
  * @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);
 }
Example #11
0
 /**
  * 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);
 }
Example #12
0
 /**
  * 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());
     }
 }
Example #13
0
 /**
  * @inheritDoc
  */
 public function get()
 {
     if (!isset($this->throwable)) {
         throw new LogicException('Throwable must be set to get view.');
     }
     ob_start();
     var_dump($this->throwable->getTrace());
     $fullTrace = ob_get_clean();
     // If xdebug is installed then var_dump is pretty printed for html already.
     if (function_exists('xdebug_var_dump')) {
         $viewTrace = new Text();
         $viewTrace->setHTML5($fullTrace);
         $fullTrace = ['div', ['class' => 'full_trace'], $viewTrace->get()];
     } else {
         $fullTrace = ['pre', ['class' => 'full_trace'], $fullTrace];
     }
     return ['div', ['class' => 'Throwable'], [['div', ['class' => 'location'], 'Thrown at ' . $this->throwable->getFile() . ' line ' . $this->throwable->getLine()], ['pre', [], $this->throwable->getMessage()], ['h2', [], 'Basic Trace'], ['pre', ['class' => 'basic_trace'], $this->throwable->getTraceAsString()], ['h2', [], 'Full Trace'], $fullTrace]];
 }
 /**
  * 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;
 }
 /**
  * @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'));
     }
 }
 /**
  * Method that returns a response in the request format
  *
  * @todo Customize according to project
  * @param string $message Error message
  * @param int $status Status code
  * @param \Exception $exception Exception caught
  * @return JsonResponse|HtmlResponse
  */
 public function getResponseFormat($message, $status, \Throwable $exception)
 {
     if (count($this->accept) > 0 && $this->accept[0] == 'application/json') {
         $data = ['status' => $status, 'error' => ['msg' => $message]];
         if ($this->debug) {
             $data['error']['debug']['msg'] = $exception->getMessage();
             $data['error']['debug']['file'] = $exception->getFile();
             $data['error']['debug']['line'] = $exception->getLine();
             $data['error']['debug']['trace'] = $exception->getTrace();
         }
         return new JsonResponse($data, $status);
     }
     $msg = $message;
     if ($this->debug) {
         $msg .= '<br />Description: ' . $exception->getMessage();
         $msg .= '<br />File: ' . $exception->getFile();
         $msg .= '<br />Line: ' . $exception->getLine();
         $msg .= '<br />Trace: ' . $exception->getTraceAsString();
     }
     return new HtmlResponse($msg, $status);
 }
Example #17
0
 /**
  * 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();
 }
Example #18
0
 /**
  * 记录起始请求日志
  * 记录成功返回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');
 }
Example #19
0
 /**
  * Makes error infos more user friendly
  *
  * @param string $errmsg;
  * @param string $filePath
  * @param string $lineNo
  */
 public static function findCallPos(\Throwable $t, string &$filePath = null, int &$lineNo = null)
 {
     if (!($t instanceof \TypeError || $t instanceof WarningError || $t instanceof RecoverableError)) {
         return;
     }
     $message = $t->getMessage();
     if (false !== strpos($message, '{closure}')) {
         return;
     }
     $fmatches = array();
     $lmatches = array();
     if (preg_match('/(?<=called in )[^ \\(]+/', $message, $fmatches) && preg_match('/((?<=on line )|(?<=\\())[0-9]+/', $message, $lmatches)) {
         $filePath = $fmatches[0];
         $lineNo = $lmatches[0];
     }
 }
 /**
  * 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);
 }
Example #21
0
 /**
  * @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());
     }
 }
Example #22
0
 /**
  * @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);
         }
     }
 }
Example #23
0
 /**
  * Get as array
  *
  * @return array
  */
 public function getDataInternal()
 {
     $result = array();
     if (is_array($this->_result)) {
         $result = array('name' => $this->_name, 'success' => $this->isSuccess());
         if ($this->_exception) {
             $result['error'] = $this->_exception->getMessage();
         }
         foreach ($this->_result as $key => $test) {
             $result['subtests'][$key] = $test->getDataInternal();
         }
     } else {
         $result = array('name' => $this->_name, 'success' => $this->isSuccess());
         if ($this->_exception) {
             $result['error'] = $this->_exception->getMessage();
         }
     }
     return $result;
 }
Example #24
0
 /**
  * @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;
 }
Example #25
0
 public function exceptionHandler(\Throwable $exception)
 {
     $message = $exception->getMessage();
     $values = $exception->getTrace();
     $traces = [];
     $trace = new Trace();
     $trace->setFile($exception->getFile());
     $trace->setLine($exception->getLine());
     $trace->setClass(get_class($exception));
     $traces[] = $trace;
     foreach ($values as $value) {
         $trace = new Trace();
         $trace->setFile($this->getArrayValue($value, "file"));
         $trace->setLine($this->getArrayValue($value, "line"));
         $trace->setFunction($this->getArrayValue($value, "function"));
         $trace->setClass($this->getArrayValue($value, "class"));
         $traces[] = $trace;
     }
     $this->log($message, $traces);
 }
Example #26
0
 /**
  * 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();
 }
Example #27
0
 /**
  * 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();
 }
Example #28
0
 /**
  * Decodes an exception and retrieves the correct caller.
  *
  * @param \Exception|\Throwable $exception
  *   The exception object that was thrown.
  *
  * @return array
  *   An error in the format expected by _drupal_log_error().
  */
 public static function decodeException($exception)
 {
     $message = $exception->getMessage();
     $backtrace = $exception->getTrace();
     // Add the line throwing the exception to the backtrace.
     array_unshift($backtrace, array('line' => $exception->getLine(), 'file' => $exception->getFile()));
     // For PDOException errors, we try to return the initial caller,
     // skipping internal functions of the database layer.
     if ($exception instanceof \PDOException || $exception instanceof DatabaseExceptionWrapper) {
         // The first element in the stack is the call, the second element gives us
         // the caller. We skip calls that occurred in one of the classes of the
         // database layer or in one of its global functions.
         $db_functions = array('db_query', 'db_query_range');
         while (!empty($backtrace[1]) && ($caller = $backtrace[1]) && (isset($caller['class']) && (strpos($caller['class'], 'Query') !== FALSE || strpos($caller['class'], 'Database') !== FALSE || strpos($caller['class'], 'PDO') !== FALSE) || in_array($caller['function'], $db_functions))) {
             // We remove that call.
             array_shift($backtrace);
         }
         if (isset($exception->query_string, $exception->args)) {
             $message .= ": " . $exception->query_string . "; " . print_r($exception->args, TRUE);
         }
     }
     $caller = static::getLastCaller($backtrace);
     return array('%type' => get_class($exception), '@message' => $message, '%function' => $caller['function'], '%file' => $caller['file'], '%line' => $caller['line'], 'severity_level' => static::ERROR, 'backtrace' => $backtrace, '@backtrace_string' => $exception->getTraceAsString());
 }
 /**
  * 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);
 }
 /**
  * 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;
 }