コード例 #1
1
 public static function factory($name, \Exception $exception)
 {
     $message = sprintf("%s could not be found. The API returned this HTTP response:\n\n%s", $name, (string) $exception->getResponse());
     $e = new self($message);
     $e->name = $name;
     $e->response = $exception->getResponse();
     $e->request = $exception->getRequest();
     return $e;
 }
コード例 #2
0
 /**
  * Sets up the custom exception and copies over original exception values.
  *
  * @param Exception $exception - the exception to be wrapped
  */
 public function __construct(\Exception $exception)
 {
     $message = $exception->getMessage();
     $code = $exception->getCode();
     if ($exception instanceof HttpException) {
         $message = $exception->getResponse()->getBody()->__toString();
         $this->body = json_decode($message, true);
         $code = $exception->getResponse()->getStatusCode();
     }
     parent::__construct($message, $code, $exception->getPrevious());
 }
コード例 #3
0
 /**
  * Put an error message corresponding to a bad response in function of the status code in the output
  *
  * @param Exception $error the exception triggered
  *
  * @return void
  */
 public function BadResponseHandler($error)
 {
     $statusCode = $error->getResponse()->getStatusCode();
     switch ($statusCode) {
         case 400:
             $this->app->setOutput("Error", "Invalid input.");
             break;
         case 401:
             $this->app->setOutput("Error", "Authentification failed.");
             break;
         case 403:
             $this->app->setOutput("Error", "Operation forbidden.");
             break;
         case 404:
             $this->app->setOutput("Error", "Ressource not found.");
             break;
         case 500:
             $this->app->setOutput("Error", "Internal server error, please contact an administrator.");
             break;
         case 503:
             $this->app->setOutput("Error", "Service unvailable for the moment.");
             break;
         default:
             $this->app->setOutput("Error", "Unknow error, please contact an administrator.");
             break;
     }
 }
コード例 #4
0
 /**
  * @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();
     }
 }
コード例 #5
0
ファイル: ExceptionTest.php プロジェクト: jstewmc/api
 /**
  * getResponse() should return response if response does exist
  */
 public function test_getResponse_returnsResponse_ifResponseDoesExist()
 {
     $response = new \Jstewmc\Api\Response\Json();
     $exception = new Exception();
     $exception->setResponse($response);
     $this->assertSame($response, $exception->getResponse());
     return;
 }
コード例 #6
0
 /**
  * Constructs a new enforced response from the given exception.
  *
  * Note that it is necessary to traverse the exception chain when searching
  * for an enforced response. Otherwise it would be impossible to find an
  * exception thrown from within a twig template.
  *
  * @param \Exception $e
  *   The exception where the enforced response is to be extracted from.
  *
  * @return \Drupal\Core\Form\EnforcedResponse|null
  *   The enforced response or NULL if the exception chain does not contain a
  *   \Drupal\Core\Form\EnforcedResponseException exception.
  */
 public static function createFromException(\Exception $e)
 {
     while ($e) {
         if ($e instanceof EnforcedResponseException) {
             return new static($e->getResponse());
         }
         $e = $e->getPrevious();
     }
 }
コード例 #7
0
 protected function _logResponseException(Exception $e)
 {
     if ($e instanceof \Payin7Payments\Exception\Payin7APIException) {
         $response = $e->getResponse();
         $code = $response->getStatusCode();
         $body = $response->getBody();
         $this->_logger->logError("[API SERVER ERROR] Status Code: {$code} | Body: {$body}");
     } else {
         $this->_logger->logError("[API SERVER ERROR] " . $e->getMessage() . ', Code: ' . $e->getCode());
     }
 }
コード例 #8
0
 /**
  * @param \Exception $exception
  * @return GuzzleRestException
  */
 public static function createFromException(\Exception $exception)
 {
     if ($exception instanceof BadResponseException && $exception->getResponse()) {
         $url = $exception->getRequest() ? (string) $exception->getRequest()->getUrl() : null;
         $result = GuzzleRestException::createFromResponse(new GuzzleRestResponse($exception->getResponse(), $url), null, $exception);
     } else {
         /** @var GuzzleRestException $result */
         $result = new static($exception->getMessage(), $exception->getCode(), $exception);
     }
     return $result;
 }
コード例 #9
0
ファイル: Panel.php プロジェクト: noikiy/Curl
 /**
  * @param \Exception $e
  *
  * @return array
  */
 public static function renderException($e)
 {
     $click = function ($o, $c = TRUE) {
         return Dumper::toHtml($o, array('collapse' => $c));
     };
     $panel = array();
     if ($e instanceof Curl\FailedRequestException) {
         $panel['info'] = '<h3>Info</h3>' . $click($e->getInfo(), TRUE);
     }
     if ($e instanceof Curl\CurlException) {
         if ($e->getRequest()) {
             $panel['request'] = '<h3>Request</h3>' . $click($e->getRequest(), TRUE);
         }
         if ($e->getResponse()) {
             $panel['response'] = '<h3>Responses</h3>' . static::allResponses($e->getResponse());
         }
     }
     if (!empty($panel)) {
         return array('tab' => 'Curl', 'panel' => implode($panel));
     }
 }
コード例 #10
0
 public function renderAsRestAPI($request, \Exception $e)
 {
     if ($e instanceof HttpResponseException) {
         return $e->getResponse();
     } elseif ($e instanceof ModelNotFoundException) {
         $e = new NotFoundHttpException($e->getMessage(), $e);
     } elseif ($e instanceof AuthorizationException) {
         $e = new HttpException(403, $e->getMessage());
     } elseif ($e instanceof ValidationException && $e->getResponse()) {
         return $e->getResponse();
     }
     $fe = FlattenException::create($e);
     $data = env("APP_DEBUG", false) ? $fe->toArray() : ["message" => "whoops, something wrong."];
     return JsonResponse::create($data, 500);
 }
コード例 #11
0
ファイル: ExceptionHandler.php プロジェクト: steefdw/bol-sdk
 /**
  * Captch known exceptions
  * @param \Exception $e
  * @throws ApiLimitException
  * @throws InvalidXmlException
  * @throws UnauthorizedException
  * @throws \Exception
  */
 public function handle(\Exception $e)
 {
     $response = $e->getResponse();
     $statusCode = $response->getStatusCode();
     if ($statusCode == 401) {
         throw new UnauthorizedException("Authorization failed. Are your public and private key correct?");
     } else {
         if ($statusCode == 400) {
             throw new InvalidXmlException();
         } else {
             if ($statusCode == 503 || $statusCode == 409) {
                 throw new ApiLimitException();
             }
         }
     }
     $body = $response->getBody(true);
     $message = $this->xmlParser->parse($body);
     if (isset($message['ErrorCode'])) {
         throw new BolException($message['ErrorCode'] . ": " . $message['ErrorMessage']);
     }
     throw new \Exception("Unknown error occurred. Status code: {$response->getStatusCode()}.");
 }
コード例 #12
0
ファイル: GApps.php プロジェクト: hybridneo/zendgdata
 /**
  * Convert an exception to an ServiceException if an AppsForYourDomain
  * XML document is contained within the original exception's HTTP
  * response. If conversion fails, throw the original error.
  *
  * @param Exception $e The exception to convert.
  * @throws GApps\ServiceException
  * @throws mixed
  */
 public static function throwServiceExceptionIfDetected($e)
 {
     // Check to make sure that there actually response!
     // This can happen if the connection dies before the request
     // completes. (See ZF-5949)
     $response = $e->getResponse();
     if (!$response) {
         throw new App\IOException('No HTTP response received (possible connection failure)');
     }
     try {
         // Check to see if there is an AppsForYourDomainErrors
         // datastructure in the response. If so, convert it to
         // an exception and throw it.
         $error = new GApps\ServiceException();
         $error->importFromString($response->getBody());
         throw $error;
     } catch (App\Exception $e2) {
         // Unable to convert the response to a ServiceException,
         // most likely because the server didn't return an
         // AppsForYourDomainErrors document. Throw the original
         // exception.
         throw $e;
     }
 }
コード例 #13
0
 /**
  * It converts all exceptions to Bluedrone Api Exceptions which are
  * in fact Problem objects. The Problem object offers
  * more details about the error that occurred.
  *
  * @param \Exception $e
  *
  * @return BluedroneException
  */
 protected function getBluedroneException(\Exception $e)
 {
     if ($e instanceof BadResponseException) {
         // if it's a 4xx or 5xx error
         $statusCode = $e->getResponse()->getStatusCode();
         $body = $e->getResponse()->getBody(true);
         $jsonBody = json_decode($body, true);
         // check to see if the server responded well behaved (with a json object)
         if ($jsonBody !== null && count($jsonBody) != 0) {
             $bluedroneException = BluedroneException::fromArray($jsonBody);
         } else {
             // if not, it means we're talking about an unrecoverable server error
             $bluedroneException = new BluedroneException('Unrecoverable Server Error', 0, "The server responded with code '{$statusCode}' but did not provide more details about the error.");
         }
     } elseif ($e instanceof RequestException) {
         // if it's a connection error
         $bluedroneException = new BluedroneException('Connection Error', 0, $e->getMessage());
     } else {
         $bluedroneException = new BluedroneException('Exception', 0, $e->getMessage());
     }
     return $bluedroneException;
 }
コード例 #14
0
ファイル: Executor.php プロジェクト: syrma-php/web-container
 /**
  * @param \Exception $ex
  *
  * @return ResponseInterface|null
  */
 private function handleInternalException(\Exception $ex)
 {
     $response = null;
     if ($ex instanceof ResponseAwareExceptionInterface) {
         $response = $ex->getResponse();
     }
     if ($ex instanceof ServerStopExceptionInterface) {
         $this->stopServerByException($ex);
     }
     return $response;
 }
コード例 #15
0
ファイル: Youtube.php プロジェクト: nlegoff/Phraseanet
 /**
  * Set The exception to Bridge_Exception_ActionAuthNeedReconnect
  * if exception is instance of Zend_Gdata_App_HttpException and Http code 401
  *
  * @param  Exception $e
  * @return Void
  */
 public function handle_exception(Exception $e)
 {
     if ($e instanceof Zend_Gdata_App_HttpException) {
         $response = $e->getResponse();
         $http_code = $response->getStatus();
         if ($http_code == 401) {
             $e = new Bridge_Exception_ActionAuthNeedReconnect();
             return;
         }
         $message = $code = "";
         switch ($response->getStatus()) {
             case 400:
                 $message = $this->translator->trans("Erreur la requête a été mal formée ou contenait des données valides.");
                 break;
             case 401:
                 $message = $this->translator->trans("Erreur lors de l'authentification au service Youtube, Veuillez vous déconnecter, puis vous reconnecter.");
                 break;
             case 403:
                 $message = $this->translator->trans("Erreur lors de l'envoi de la requête. Erreur d'authentification.");
                 break;
             case 404:
                 $message = $this->translator->trans("Erreur la ressource que vous tentez de modifier n'existe pas.");
                 break;
             case 500:
                 $message = $this->translator->trans("Erreur YouTube a rencontré une erreur lors du traitement de la requête.");
                 break;
             case 501:
                 $message = $this->translator->trans("Erreur vous avez essayé d'exécuter une requête non prise en charge par Youtube");
                 break;
             case 503:
                 $message = $this->translator->trans("Erreur le service Youtube n'est pas accessible pour le moment. Veuillez réessayer plus tard.");
                 break;
         }
         if ($error = $this->parse_xml_error($response->getBody())) {
             $code = $error['code'];
             if ($code == "too_many_recent_calls") {
                 $this->block_api(10 * 60 * 60);
                 $e = new Bridge_Exception_ApiDisabled($this->get_api_manager());
                 return;
             }
             $reason = '';
             switch ($code) {
                 case "required":
                     $reason = $this->translator->trans("A required field is missing or has an empty value");
                     break;
                 case "deprecated":
                     $reason = $this->translator->trans("A value has been deprecated and is no longer valid");
                     break;
                 case "invalid_format":
                     $reason = $this->translator->trans("A value does not match an expected format");
                     break;
                 case "invalid_character":
                     $reason = $this->translator->trans("A field value contains an invalid character");
                     break;
                 case "too_long":
                     $reason = $this->translator->trans("A value exceeds the maximum allowable length");
                     break;
                 case "too_many_recent_calls":
                     $reason = $this->translator->trans("The Youtube servers have received too many calls from the same caller in a short amount of time.");
                     break;
                 case "too_many_entries":
                     $reason = $this->translator->trans("You are attempting to exceed the storage limit on your account and must delete existing entries before inserting new entries");
                     break;
                 case "InvalidToken":
                     $reason = $this->translator->trans("The authentication token specified in the Authorization header is invalid");
                     break;
                 case "TokenExpired":
                     $reason = $this->translator->trans("The authentication token specified in the Authorization header has expired.");
                     break;
                 case "disabled_in_maintenance_mode":
                     $reason = $this->translator->trans("Current operations cannot be executed because the site is temporarily in maintenance mode. Wait a few minutes and try your request again");
                     break;
             }
             $message .= '<br/>' . $reason . '<br/>Youtube said : ' . $error['message'];
         }
         if ($error == false && $response->getStatus() == 404) {
             $message = $this->translator->trans("Service youtube introuvable.");
         }
         $e = new Exception($message);
     }
     return;
 }
コード例 #16
0
ファイル: Panel.php プロジェクト: EaredSeal/ElasticSearch
 /**
  * @param \Exception|\Throwable $e
  * @return array|NULL
  */
 public static function renderException($e = NULL)
 {
     if (!$e instanceof ExceptionInterface) {
         return NULL;
     }
     $panel = NULL;
     if ($e instanceof Elastica\Exception\ResponseException) {
         $panel .= '<h3>Request</h3>';
         $panel .= Dumper::toHtml($e->getRequest());
         $panel .= '<h3>Response</h3>';
         $panel .= Dumper::toHtml($e->getResponse());
     } elseif ($e instanceof Elastica\Exception\Bulk\ResponseException) {
         $panel .= '<h3>Failures</h3>';
         $panel .= Dumper::toHtml($e->getFailures());
     }
     /*elseif ($e->getQuery() !== NULL) {
     			$panel .= '<h3>Query</h3>'
     				. '<pre class="nette-dump"><span class="php-string">'
     				. $e->getQuery()->getQuery()
     				. '</span></pre>';
     		} */
     return $panel ? array('tab' => 'ElasticSearch', 'panel' => $panel) : NULL;
 }
コード例 #17
0
ファイル: Panel.php プロジェクト: Hajneej/PayPalExpress
 /**
  * @param \Exception $e
  * @return array
  */
 public static function renderException($e)
 {
     if ($e instanceof PayPal\ErrorResponseException) {
         return array('tab' => 'PayPalRequest', 'panel' => '<p><b>Request:</b></p>' . Nette\Diagnostics\Helpers::clickableDump($e->getData(), TRUE) . '<p><b>Response:</b></p>' . Nette\Diagnostics\Helpers::clickableDump($e->getResponse(), TRUE));
     }
 }
コード例 #18
0
ファイル: StravaDownloader.php プロジェクト: robcaw/stravadl
 public function exceptionThrower(\Exception $e)
 {
     $status_code = $e->getResponse()->getStatusCode();
     if ($status_code == 401) {
         throw new UnauthorizedException();
     } elseif ($status_code == 403) {
         throw new \Exception("Limit reached/Not authorised");
     } else {
         throw $e;
     }
 }
コード例 #19
0
 protected function _logResponseException(\Exception $e)
 {
     if ($e instanceof Payin7APIException) {
         $response = $e->getResponse();
         $code = $response->getStatusCode();
         $body = $response->getBody();
         error_log("[API SERVER ERROR] Status Code: {$code} | Body: {$body}");
     } else {
         error_log("[API SERVER ERROR] " . $e->getMessage() . ', Code: ' . $e->getCode());
     }
 }
コード例 #20
0
ファイル: manager.php プロジェクト: cepharum/txf
 /**
  * Catches exceptions not catched in code for embedding rendered exception
  * description in selected page design (if possible).
  *
  * @param \Exception $exception
  */
 public function onException(\Exception $exception)
 {
     if ($exception instanceof \ErrorException) {
         if ($exception->getCode() & E_NOTICE) {
             return;
         }
     }
     if ($exception instanceof \de\toxa\txf\http_exception) {
         header($exception->getResponse());
     }
     $this->accessVariable('exception', $exception);
     static::addBodyClass('exception');
     try {
         try {
             $code = $this->engine->render('exception', variable_space::create('exception', $exception));
         } catch (\Exception $e) {
             $code = locale::get('failed to render exception');
         }
         $this->viewport('error', $code);
         if (txf::getContextMode() == txf::CTXMODE_REWRITTEN) {
             // this mode does not have registered shutdown handler
             // --> call it explicitly here
             $this->onShutdown();
         }
     } catch (\Exception $e) {
         echo '<h1>Failed to render exception</h1>';
         echo self::simpleRenderException($exception);
         echo '<h1>Encountered error was</h1>';
         echo self::simpleRenderException($e);
     }
     exit;
 }
コード例 #21
0
 /**
  * Handle a failed response coming back when getting temporary credentials.
  *
  * @since  0.2.3
  *
  * @param Exception $e
  *
  * @throws CredentialsException
  */
 public function handleTemporaryCredentialsFail($e)
 {
     $response = $e->getResponse();
     if (500 === $response->getStatusCode()) {
         $body = __('It is possible the Callback URL is invalid. Please check.', 'wds-wp-rest-api-connect');
         $response->setBody($body);
     }
     return $this->handleTemporaryCredentialsBadResponse($e);
 }
コード例 #22
0
ファイル: HTTPClient.php プロジェクト: padosoft/httpclient
 /**
  * @param \Exception $e
  * @return string
  */
 public function getResponseStatusCodeFromException(\Exception $e)
 {
     if (null === $e->getResponse()) {
         return '';
     }
     if (!is_a($e->getResponse(), '\\GuzzleHttp\\Psr7\\Response')) {
         return '';
     }
     $responseStatusCode = $e->getResponse()->getStatusCode();
     return $responseStatusCode;
 }
コード例 #23
0
 /**
  * This function attempts to parse the exceptions that are recieved from
  * Fedora into something more reasonable. This it very hard since really
  * things like this are garbage in garbage out, but we do what we can.
  *
  * @param Exception $e
  *   The exception being parsed
  */
 protected function parseFedoraExceptions($e)
 {
     $code = $e->getCode();
     switch ($code) {
         case '400':
             // When setting an error 400 often Fedora puts useful error messages
             // in the message body, we might as well expose them.
             $response = $e->getResponse();
             $message = $response['content'];
             if (!$message || strpos($message, 'Exception') !== FALSE) {
                 $message = $e->getMessage();
             }
             break;
         case '500':
             // When setting an error 500 Fedora is usually returning a java stack
             // trace. This isn't great, but we can give a better message by return
             // the message set in that exception .
             $response = $e->getResponse();
             $message = preg_split('/$\\R?^/m', $response['content']);
             $message = $message[0];
             break;
         default:
             $message = $e->getMessage();
             break;
     }
     throw new RepositoryException($message, $code, $e);
 }
コード例 #24
0
ファイル: SecureHttpClient.php プロジェクト: acmephp/core
 private function handleClientException(Request $request, \Exception $exception)
 {
     if ($exception instanceof RequestException && $exception->getResponse() instanceof ResponseInterface) {
         $this->lastResponse = $exception->getResponse();
         throw $this->errorHandler->createAcmeExceptionForResponse($request, $this->lastResponse, $exception);
     }
     throw new AcmeCoreClientException(sprintf('An error occured during request "%s %s"', $request->getMethod(), $request->getUri()), $exception);
 }
コード例 #25
0
 /**
  * Gets the exception message.
  *
  * @param \Exception $ex
  * @return string
  */
 private function getExceptionMessage(\Exception $ex)
 {
     if ($ex instanceof RequestException && $ex->hasResponse()) {
         $res = (string) $ex->getResponse()->getBody();
         json_decode($res);
         if (json_last_error() === JSON_ERROR_NONE) {
             return $res;
         }
     }
     return $ex->getMessage();
 }
コード例 #26
0
 /**
  * Gets the exception message.
  *
  * @param \Exception $ex
  * @return string
  */
 private function getExceptionMessage(\Exception $ex)
 {
     if ($ex instanceof RequestException && $ex->hasResponse()) {
         return (string) $ex->getResponse()->getBody();
     }
     return $ex->getMessage();
 }