Example #1
2
 public static function exception(Exception $e)
 {
     $code = $e->getCode();
     $message = $e->getMessage();
     switch (self::$_CODE[$code]) {
         case 'DATA_NOT_FOUND':
             self::_dataNotFound($message);
             break;
         case 'CLASS_NOT_FOUND':
             self::_classNotFound($message);
             break;
         case 'METHOD_NOT_FOUND':
             self::_methodNotFound($message);
             break;
         case 'FILE_NOT_FOUND':
             self::_fileNotFound($message);
             break;
         case 'DIRECTORY_NOT_FOUND':
             self::_directoryNotFound($message);
             break;
         case 'SERVER_OVERLOADING':
             self::_serverOverloading($message);
             break;
         default:
             self::_dataNotFound($message);
             break;
             exit;
     }
 }
Example #2
1
 public function __construct($message = '', $code = 0, Exception $e = null)
 {
     if ($e && 0 === $code) {
         $code = $e->getCode();
     }
     parent::__construct($message, $code, $e);
 }
Example #3
1
 /**
  * @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;
 }
Example #4
1
 public static function exceptionHandle(Exception $exception)
 {
     if (DEBUG_MODE) {
         //直接输出调试信息
         echo nl2br($exception->__toString());
         echo '<hr /><p>Router:</p><pre>';
         print_r(Singleton::getInstance('Router'));
         echo '</pre>';
     } else {
         $code = $exception->getCode();
         $message = nl2br($exception->getMessage());
         /*
                     如果错误码"可能为"合法的http状态码则尝试设置,
                     setStatus()方法会忽略非法的http状态码. */
         if ($code >= 400 && $code <= 505 && !headers_sent()) {
             ResponseModule::setStatus($code);
         }
         $var_list = array('message' => $message, 'code' => $code, 'file' => $exception->getFile(), 'url' => Singleton::getInstance('Router')->getUrl());
         if ($error_file = self::_getErrorFilePath($code)) {
             Lugit::$view = new View($var_list);
             Lugit::$view->render($error_file);
         } else {
             echo 'No error page is found.<pre>';
             print_r($var_list);
             echo '</pre>';
         }
     }
     exit;
 }
Example #5
1
 public function onNotSuccessfulTest(Exception $e)
 {
     if ($e instanceof Horde_Imap_Client_Exception) {
         $e->setMessage($e->getMessage() . ' [' . self::$live->url . ']');
     }
     parent::onNotSuccessfulTest($e);
 }
 /**
  * Error handler which publishes all errors thrown by code which doesn't use
  * structured exception handling
  *
  * @param int $errno
  * @param string $errstr
  * @param string $errfile
  * @param int $errline
  * @param array $errcontext
  */
 public function ErrorHandler($errno, $errstr, $errfile, $errline, array $errcontext)
 {
     $additional_info = array('File' => $errfile, 'Line' => $errline, 'Context' => $errcontext);
     $e = new Exception($errstr, $errno);
     switch ($e->getCode()) {
         # Not serious, ignore
         case E_STRICT:
             break;
             # Not serious, log and carry on unless on a WordPress page.
             # WordPress developers don't fix these, so if this is a WordPress page ignore it.
         # Not serious, log and carry on unless on a WordPress page.
         # WordPress developers don't fix these, so if this is a WordPress page ignore it.
         case E_NOTICE:
         case E_USER_NOTICE:
             if (!function_exists('wp')) {
                 $this->Publish($e, $additional_info);
             }
             break;
             # Not serious, log and carry on
         # Not serious, log and carry on
         case E_WARNING:
         case E_USER_WARNING:
             $this->Publish($e, $additional_info);
             break;
             # Serious, log and die
         # Serious, log and die
         default:
             $this->Publish($e, $additional_info);
             if (!headers_sent()) {
                 header("HTTP/1.1 500 Internal Server Error");
             }
             die('<p class="validationSummary">Sorry, there\'s a problem with this page. Please try again later.</p>');
     }
 }
 /**
  * @param string     $resource       The resource that could not be imported
  * @param string     $sourceResource The original resource importing the new resource
  * @param int        $code           The error code
  * @param \Exception $previous       A previous exception
  */
 public function __construct($resource, $sourceResource = null, $code = null, $previous = null)
 {
     $message = '';
     if ($previous) {
         // Include the previous exception, to help the user see what might be the underlying cause
         // Trim the trailing period of the previous message. We only want 1 period remove so no rtrim...
         if ('.' === substr($previous->getMessage(), -1)) {
             $trimmedMessage = substr($previous->getMessage(), 0, -1);
             $message .= sprintf('%s', $trimmedMessage) . ' in ';
         } else {
             $message .= sprintf('%s', $previous->getMessage()) . ' in ';
         }
         $message .= $resource . ' ';
         // show tweaked trace to complete the human readable sentence
         if (null === $sourceResource) {
             $message .= sprintf('(which is loaded in resource "%s")', $this->varToString($resource));
         } else {
             $message .= sprintf('(which is being imported from "%s")', $this->varToString($sourceResource));
         }
         $message .= '.';
         // if there's no previous message, present it the default way
     } elseif (null === $sourceResource) {
         $message .= sprintf('Cannot load resource "%s".', $this->varToString($resource));
     } else {
         $message .= sprintf('Cannot import resource "%s" from "%s".', $this->varToString($resource), $this->varToString($sourceResource));
     }
     // Is the resource located inside a bundle?
     if ('@' === $resource[0]) {
         $parts = explode(DIRECTORY_SEPARATOR, $resource);
         $bundle = substr($parts[0], 1);
         $message .= ' ' . sprintf('Make sure the "%s" bundle is correctly registered and loaded in the application kernel class.', $bundle);
     }
     parent::__construct($message, $code, $previous);
 }
 /**
  * @param \Exception $exception
  * @return \Illuminate\Http\JsonResponse
  */
 public function format($exception)
 {
     // Define the response
     $result = ['errors' => trans('messages.sorry')];
     // Default response of 400
     $statusCode = 400;
     $addDebugData = $this->isDebugEnabled();
     switch (true) {
         case $exception instanceof HttpException:
             $statusCode = $exception->getStatusCode();
             $result['errors'] = $exception->getMessage();
             break;
         case $exception instanceof ValidationException:
             $result['errors'] = $exception->errors();
             $addDebugData = false;
             break;
     }
     // Prepare response
     $response = ['success' => false, 'result' => $result, 'meta' => ['version' => config('app.version.api'), 'request' => \Request::method() . ' ' . \Request::url(), 'debug' => $this->isDebugEnabled()]];
     // If the app is in debug mode && not Validation exception
     if ($addDebugData) {
         $response['debug'] = ['exception' => get_class($exception), 'message' => $exception->getMessage(), 'file' => $exception->getFile(), 'line' => $exception->getLine(), 'trace' => $exception->getTrace()];
     }
     // Return a JSON response with the response array and status code
     return response()->json($response, $statusCode);
 }
Example #9
0
 public static function createExceptionResponse(\Exception $ex)
 {
     $response = new Response();
     $response->success = false;
     array_push($response->errors, $ex->getMessage());
     return $response;
 }
Example #10
0
 /**
  * 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;
 }
Example #11
0
 private function generateErrorForException(\Exception $exception)
 {
     if ($exception instanceof CommandInvalidException) {
         $formError = $exception->getForm()->getErrors(true)->current();
         $path = $formError->getOrigin()->getPropertyPath();
         if ($path !== null) {
             // We got PropertyPathInterface or maybe even a string (undocumented).
             $path = (string) $path;
         }
         return new E\Api\BadRequest($formError->getMessage(), $path);
     } elseif ($exception instanceof ConstraintViolationException) {
         return $exception->getError();
     } elseif ($exception instanceof UsernameNotFoundException) {
         return new E\Security\BadCredentials();
     } elseif ($exception instanceof AccessDeniedException) {
         $token = $this->tokenStorage->getToken();
         if ($token && $this->tokenStorage->getToken()->getRoles()) {
             return new E\Security\NotAuthorized();
         } else {
             return new E\Security\NotAuthenticated();
         }
     } elseif ($exception instanceof ProtocolException) {
         return $this->getErrorForOxygenProtocolException($exception);
     } else {
         return new E\Api\UnexpectedError();
     }
 }
Example #12
0
/**
 * Catch Exceptions
 * @param Exception $err
 */
function catchExceptions($err)
{
    global $config;
    echo "Error with your request!  Please try again later.  " . "If the problem persists contact <a href=\"" . $config['contact'] . "\">" . $config['contact'] . "</a>.";
    error_log($err->__toString(), 0);
    exit(1);
}
Example #13
0
function drop()
{
    call_user_func_array("var_dump", func_get_args());
    $e = new Exception();
    echo "-------\nDump trace: \n" . $e->getTraceAsString() . "\n";
    exit;
}
 /**
  * Log errors.
  *
  * @param \Exception $e
  * @param $serverName
  * @param $type
  * @return string
  */
 protected function serverErrorHandler(\Exception $e, $serverName, $type)
 {
     $errorMessage = "Error in server " . $serverName . ': ' . $e->getMessage();
     $this->getLogger()->addError($errorMessage);
     $this->getLogger()->addDebug($e);
     return $errorMessage;
 }
Example #15
0
 /**
  * Ставим хук на вызов неизвестного метода и считаем что хотели вызвать метод какого либо модуля
  * @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;
     }
 }
Example #16
0
/**
 * 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);
}
Example #17
0
 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;
 }
Example #18
0
 /**
  * Handle exception
  *
  * @param \Exception $e
  * @return void
  */
 protected function handleException($e)
 {
     $needToMaskDisplayMessage = !$e instanceof \Magento\Framework\Exception\LocalizedException && $this->appState->getMode() != State::MODE_DEVELOPER;
     $displayMessage = $needToMaskDisplayMessage ? (string) new \Magento\Framework\Phrase('An error occurred while processing your request') : $e->getMessage();
     $this->messageManager->addError($displayMessage);
     $this->logger->critical($e->getMessage());
 }
Example #19
0
 /**
  * @param \Exception $e
  * @param bool $terminate
  */
 public function exception(\Exception $e, $terminate = true)
 {
     $html_message = '';
     $id = hash('md4', $e->getMessage() . $e->getFile() . $e->getLine());
     if (!$e instanceof \ErrorException) {
         $html_message = '<strong>- Uncaught exception: </strong> ' . get_class($e) . "<br />\n";
     }
     $html_message .= '<strong>- Message:</strong> ' . $e->getMessage();
     if ($this->mode == 'development') {
         $html_message .= "<br />\n<strong>- File:</strong> " . $e->getFile() . "<br />\n<strong>- Line:</strong> " . $e->getLine() . "<br />\n<strong>- Code:</strong> " . $e->getCode();
     }
     $html_message .= "<br />\n<strong>- ID:</strong> {$id}";
     $log_body = trim(strip_tags($html_message));
     // If we're in production/test the html message will not
     // contain info about the file where the error appeared
     // therefor we add it to error log here
     if ($this->mode != 'development') {
         $log_body .= "\n- File: " . $e->getFile() . "\n- Line: " . $e->getLine() . "\n- Code: " . $e->getCode();
     }
     $log_message = '### Error ' . (empty($_SERVER['REQUEST_URI']) ? '' : $_SERVER['REQUEST_URI']) . (empty($_SERVER['REQUEST_METHOD']) ? '' : ' (' . $_SERVER['REQUEST_METHOD'] . ')') . (empty($_SERVER['REMOTE_ADDR']) ? '' : ' ' . $_SERVER['REMOTE_ADDR']) . "\n" . $log_body . "\n" . $e->getTraceAsString();
     if ($this->mode == 'development') {
         $html_message .= "\n<p>" . nl2br($e->getTraceAsString()) . "</p>\n";
     } else {
         $html_message .= "\n<p><em>Stack trace and full error message available in the error log</em></p>\n";
     }
     $html_message = '<h2>PHP Error</h2>' . $html_message;
     error_log($log_message);
     if ($terminate) {
         if (!headers_sent()) {
             header('HTTP/1.1 500 Internal Server Error');
         }
         echo $html_message;
         die;
     }
 }
Example #20
0
 /**
  * Handle exception
  * 
  * @param Exception $exception Exception object
  * @return void
  */
 public function handleException(Exception $exception)
 {
     echo "\n";
     $this->_terminal->pretty_message($exception->getMessage(), 7, 1);
     echo "\n";
     exit(1);
 }
 public static function draw(\Exception $oExp)
 {
     @header($_SERVER['SERVER_PROTOCOL'] . ' 500 Internal Server Error', true, 500);
     $oResponse = new Response();
     $oResponse->setData(array('success' => false, 'error' => $oExp->getMessage(), 'errorDetail' => array('type' => get_class($oExp), 'code' => $oExp->getCode())));
     return $oResponse->flushJson();
 }
Example #22
0
 /**
  * Resolve user by identity
  *
  * @param  string      $identity
  * @param  string|null $realm
  * @param  string|null $password
  * @return \Zend\Authentication\Result
  * @throws \RuntimeException if cannot read passwords file
  */
 public function resolve($identity, $realm = null, $password = null)
 {
     set_error_handler([$this, 'handleError'], E_WARNING);
     $fp = fopen($this->file, 'r');
     restore_error_handler();
     if (!$fp) {
         throw new \RuntimeException('Unable to open password file: ' . $this->file . ' reason ' . $this->error->getMessage());
     }
     $matchedHash = null;
     while (($line = fgetcsv($fp, 512, ':')) !== false) {
         if ($line[0] !== $identity) {
             continue;
         }
         if (isset($line[2])) {
             if ($line[1] === $realm) {
                 $matchedHash = $line[2];
                 break;
             }
             continue;
         }
         $matchedHash = $line[1];
         break;
     }
     fclose($fp);
     if (empty($matchedHash)) {
         return Result::failureIdentityNotFound();
     }
     return Result::success([new User($identity, $matchedHash, $this->roles)]);
 }
Example #23
0
 /**
  * appends the given reference code to the exception's message
  * unless it is unset
  *
  * @param \Exception $exception
  * @param $referenceCode
  * @return string
  */
 protected function getMessage(\Exception $exception, $referenceCode)
 {
     if (isset($referenceCode)) {
         return sprintf('%s (%s)', $exception->getMessage(), $referenceCode);
     }
     return $exception->getMessage();
 }
 /**
  * @param array $items
  */
 public function write(array $items)
 {
     //file_put_contents('product_association.json', json_encode($items));
     foreach ($items as $item) {
         try {
             // Send only when association exist
             if (count($item[key($item)]) > 0) {
                 $this->webservice->sendAssociation($item);
             }
         } catch (\Exception $e) {
             $event = new InvalidItemEvent(__CLASS__, $e->getMessage(), array(), ['sku' => array_key_exists('sku', $item) ? $item['sku'] : 'NULL']);
             // Logging file
             $this->eventDispatcher->dispatch(EventInterface::INVALID_ITEM, $event);
             // Loggin Interface
             $this->stepExecution->addWarning(__CLASS__, $e->getMessage(), array(), ['sku' => array_key_exists('sku', $item) ? $item['sku'] : 'NULL']);
             /** @var ClientErrorResponseException  $e */
             if ($e->getResponse()->getStatusCode() <= 404) {
                 $e = new \Exception($e->getResponse()->getReasonPhrase());
                 $this->stepExecution->addFailureException($e);
                 $exitStatus = new ExitStatus(ExitStatus::FAILED);
                 $this->stepExecution->setExitStatus($exitStatus);
             }
             // Handle next element.
         }
         $this->stepExecution->incrementSummaryInfo('write');
         $this->stepExecution->incrementWriteCount();
     }
 }
 protected function onFailure(Request $request, \Exception $failed)
 {
     if (null !== $this->logger) {
         $this->logger->debug(sprintf('Authentication request failed: %s', $failed->getMessage()));
     }
     $this->securityContext->setToken(null);
     if (null === $this->options['failure_path']) {
         $this->options['failure_path'] = $this->options['login_path'];
     }
     if ($this->options['failure_forward']) {
         if (null !== $this->logger) {
             $this->logger->debug(sprintf('Forwarding to %s', $this->options['failure_path']));
         }
         $subRequest = Request::create($this->options['failure_path']);
         $subRequest->attributes->set(SecurityContext::AUTHENTICATION_ERROR, $failed->getMessage());
         return $event->getSubject()->handle($subRequest, HttpKernelInterface::SUB_REQUEST);
     } else {
         if (null !== $this->logger) {
             $this->logger->debug(sprintf('Redirecting to %s', $this->options['failure_path']));
         }
         $request->getSession()->set(SecurityContext::AUTHENTICATION_ERROR, $failed->getMessage());
         $response = new Response();
         $response->setRedirect(0 !== strpos($this->options['failure_path'], 'http') ? $request->getUriForPath($this->options['failure_path']) : $this->options['failure_path'], 302);
         return $response;
     }
 }
Example #26
0
 public function validationError($field, $data, \Exception $e)
 {
     $fex = new ValidatorException(sprintf($this->standardMessage, $field, $e->getMessage(), $e->getCode()), $e->getCode(), $e);
     $fex->field = $field;
     $fex->data = $data;
     return $fex;
 }
Example #27
0
 /**
  * Render response body
  * @param  array      $env
  * @param  \Exception $exception
  * @return string
  */
 protected function renderBody(&$env, $exception)
 {
     $title = 'Slim Application Error';
     $code = $exception->getCode();
     $message = $exception->getMessage();
     $file = $exception->getFile();
     $line = $exception->getLine();
     $trace = $exception->getTraceAsString();
     $html = sprintf('<h1>%s</h1>', $title);
     $html .= '<p>The application could not run because of the following error:</p>';
     $html .= '<h2>Details</h2>';
     $html .= sprintf('<div><strong>Type:</strong> %s</div>', get_class($exception));
     if ($code) {
         $html .= sprintf('<div><strong>Code:</strong> %s</div>', $code);
     }
     if ($message) {
         $html .= sprintf('<div><strong>Message:</strong> %s</div>', $message);
     }
     if ($file) {
         $html .= sprintf('<div><strong>File:</strong> %s</div>', $file);
     }
     if ($line) {
         $html .= sprintf('<div><strong>Line:</strong> %s</div>', $line);
     }
     if ($trace) {
         $html .= '<h2>Trace</h2>';
         $html .= sprintf('<pre>%s</pre>', $trace);
     }
     return sprintf("<html><head><title>%s</title><style>body{margin:0;padding:30px;font:12px/1.5 Helvetica,Arial,Verdana,sans-serif;}h1{margin:0;font-size:48px;font-weight:normal;line-height:48px;}strong{display:inline-block;width:65px;}</style></head><body>%s</body></html>", $title, $html);
 }
 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;
 }
Example #29
0
 public static function create(\Exception $e)
 {
     $message = $e->getMessage();
     $code = 0;
     switch (true) {
         case 0 === strpos($message, 'Failed to connect. Code '):
         case 0 === strpos($message, 'Invalid primary port value: '):
             return new ConnectionException($message);
         case 0 === strpos($message, 'Query error '):
             $pos = strpos($message, ':', 12);
             $code = (int) substr($message, 12, $pos - 12);
             $message = substr($message, $pos + 2);
             break;
         case 0 === strpos($message, 'No space'):
             $message = preg_replace("/No space '([^']+?)' defined/", "Space '\\1' does not exist'", $message);
             break;
         case 0 === strpos($message, 'Field OP must be provided and must be'):
         case 0 === strpos($message, 'Five fields must be provided for splice at position'):
             $message = 'Unknown UPDATE operation';
             $code = 28;
             break;
         case 0 === strpos($message, 'Op must be MAP at pos'):
             $message = 'Illegal parameters, update operation must be an array {op,..}, got empty array';
             $code = 1;
             break;
     }
     return new Exception($message, $code, $e);
 }
 public function loadData($pid, $name, $tmpDir)
 {
     // Upload to WebDav
     $webDav = new WebDav($this->gdClient->getUsername(), $this->gdClient->getPassword(), $this->gdClient->getUserUploadUrl());
     $dimensionName = Identifiers::getIdentifier($name);
     $tmpFolderNameDimension = "{$pid}-{$dimensionName}-" . uniqid();
     $tmpFolderDimension = $tmpDir . '/' . Identifiers::getIdentifier($name);
     mkdir($tmpFolderDimension);
     $timeDimensionManifest = self::getDataLoadManifest($dimensionName);
     file_put_contents("{$tmpFolderDimension}/upload_info.json", $timeDimensionManifest);
     copy(__DIR__ . '/time-dimension.csv', "{$tmpFolderDimension}/{$dimensionName}.csv");
     $webDav->createFolder($tmpFolderNameDimension);
     $webDav->upload("{$tmpFolderDimension}/upload_info.json", $tmpFolderNameDimension);
     $webDav->upload("{$tmpFolderDimension}/{$dimensionName}.csv", $tmpFolderNameDimension);
     // Run ETL task of time dimensions
     try {
         $this->gdClient->getDatasets()->loadData($pid, $tmpFolderNameDimension);
     } catch (Exception $e) {
         $debugFile = "{$tmpFolderDimension}/{$pid}-etl.log";
         $logSaved = $webDav->saveLogs($tmpFolderDimension, $debugFile);
         if ($logSaved) {
             $data = file_get_contents($debugFile);
             if ($data) {
                 $data = json_decode($data, true);
                 if ($data) {
                     $e = new Exception(json_decode(file_get_contents($debugFile), true), $e->getCode(), $e);
                 }
             }
         }
         throw $e;
     }
 }