Esempio n. 1
0
 protected function handleBadResponse(BadResponseException $e)
 {
     if ($e->getResponse()->getStatusCode() == 404) {
         $this->storage->delete($e->getRequest());
         throw $e;
     }
 }
 public static function fromBadResponseException(BadResponseException $old)
 {
     $new = new self($old->getMessage());
     $new->setRequest($old->getRequest());
     $new->setResponse($old->getResponse());
     return $new;
 }
 public static function factory(BadResponseException $exception)
 {
     $response = $exception->getResponse();
     $message = sprintf("This operation was forbidden; the API returned a %s status code with this message:\n%s", $response->getStatusCode(), (string) $response->getBody());
     $e = new self($message);
     $e->setResponse($response);
     $e->setRequest($exception->getRequest());
     return $e;
 }
 /**
  * @param  BadResponseException $previous
  * @return XsollaAPIException
  */
 public static function fromBadResponse(BadResponseException $previous)
 {
     $statusCode = $previous->getResponse()->getStatusCode();
     $message = sprintf(static::$messageTemplate, $previous->getMessage(), $previous->getRequest(), $previous->getResponse());
     if (array_key_exists($statusCode, static::$exceptions)) {
         return new static::$exceptions[$statusCode]($message, 0, $previous);
     }
     return new self($message, 0, $previous);
 }
 /**
  * Handles a bad response when attempting to revalidate
  *
  * @param BadResponseException $e Exception encountered
  *
  * @throws BadResponseException
  */
 protected function handleBadResponse(BadResponseException $e)
 {
     // 404 errors mean the resource no longer exists, so remove from
     // cache, and prevent an additional request by throwing the exception
     if ($e->getResponse()->getStatusCode() == 404) {
         $this->storage->delete($e->getRequest());
         throw $e;
     }
 }
 /**
  * @param BadResponseException error
  *
  * @return string
  */
 public function getErrorMessage(BadResponseException $error)
 {
     $jsonResponse = json_decode($error->getResponse()->getBody(), true);
     $errorMessage = $error->getMessage();
     if (count($jsonResponse['errors']) > 0) {
         $errorMessage = $jsonResponse['errors'][0]['message'];
     }
     return $errorMessage;
 }
 public static function factory(BadResponseException $exception)
 {
     $response = $exception->getResponse();
     $message = sprintf("This resource you were looking for could not be found; the API returned a %s status code with this message:\n%s", $response->getStatusCode(), (string) $response->getBody());
     $e = new self($message);
     $e->setResponse($response);
     $e->setRequest($exception->getRequest());
     return $e;
 }
 /**
  * @param Event $event
  */
 public function onRequestSent(Event $event)
 {
     $body = json_decode($event['response']->getBody(true), true);
     if (!isset($body['ok']) || !$body['ok']) {
         throw BadResponseException::factory($event['request'], $event['response']);
     }
 }
 /**
  * @covers Guzzle\Http\Exception\BadResponseException::factory
  */
 public function testCreatesServerErrorExceptionOnServerError()
 {
     $request = new Request('GET', 'http://www.example.com');
     $response = new Response(503);
     $e = BadResponseException::factory($request, $response);
     $this->assertInstanceOf('Guzzle\\Http\\Exception\\ServerErrorResponseException', $e);
 }
Esempio n. 10
0
 /**
  * @expectedException League\OAuth2\Client\Exception\IDPException
  */
 public function testGetAccessTokenFailure()
 {
     $response = m::mock('Guzzle\\Http\\Message\\Response');
     $response->shouldReceive('getBody')->times(1)->andReturn('{"type": "internal_server_error", "message": "Something went wrong"}');
     $exception = new BadResponseException();
     $exception->setResponse($response);
     $request = m::mock('Guzzle\\Http\\Message\\Request');
     $request->shouldReceive('setBody')->with($body = m::type('string'), $type = 'application/json')->times(1)->andReturn($request);
     $request->shouldReceive('send')->times(1)->andThrow($exception);
     $client = m::mock('Guzzle\\Service\\Client');
     $client->shouldReceive('post')->with($this->provider->urlRenewToken(), m::on(function ($headers) {
         return !empty($headers['Authorization']) && strpos($headers['Authorization'], 'Client') === 0;
     }))->times(1)->andReturn($request);
     $this->provider->setHttpClient($client);
     $this->provider->getAccessToken('renew_token', ['access_token' => 'mock_token']);
 }
Esempio n. 11
0
 /**
  * @dataProvider getErrorMapping
  * @param string $httpMethod
  * @param int    $statusCode
  * @param string $description
  */
 public function testErrorDescriptions($httpMethod, $statusCode, $description)
 {
     $request = RequestFactory::getInstance()->fromMessage("{$httpMethod} /container/ HTTP/1.1\r\n" . "Host: www.foo.bar\r\n");
     $response = new Response($statusCode);
     $prevException = BadResponseException::factory($request, $response);
     $httpException = HttpException::factory($prevException);
     $this->assertEquals($description, $httpException->getDescription());
 }
Esempio n. 12
0
 /**
  * {@inheritdoc}
  */
 public function getXML($resource, array $params = array(), array $headers = array(), array $options = array())
 {
     $response = $this->get($resource, $params, $headers, $options);
     if (!$response->isSuccessful()) {
         throw GuzzleRestException::createFromException(BadResponseException::factory($this->lastGuzzleRequest, $response->getSourceResponse()));
     }
     return $response->xml();
 }
Esempio n. 13
0
 public function testIsAuthenticationValidServerError()
 {
     $that = $this;
     $request = $this->createMockRequest(function ($request) use($that) {
         return $that->throwException(BadResponseException::factory($request, $that->createMockResponse()));
     });
     $this->getMockHttpClient()->expects($this->once())->method('post')->will($this->returnValue($request));
     $this->setExpectedException('Guzzle\\Http\\Exception\\BadResponseException');
     $this->assertFalse($this->resource->isAuthenticationValid('foo', 'bar'));
 }
Esempio n. 14
0
 public function testSendHandlesBadResponseException()
 {
     $request = new Request('GET', 'https://example.com');
     $expected = new Response(200, null, 'sometest');
     $clientMock = $this->getGuzzleClientMock(array('send'));
     $clientMock->expects($this->once())->method('send')->with($request)->will($this->throwException(BadResponseException::factory($request, $expected)));
     $httpClient = new HttpClient($clientMock);
     $actual = $httpClient->send($request);
     $this->assertEquals($expected, $actual, 'Expected response from BadResponseException.');
 }
Esempio n. 15
0
 /**
  * @param BadResponseException $cause
  *
  * @return self
  */
 public static function factory(BadResponseException $cause)
 {
     $request = $cause->getRequest();
     $response = $cause->getResponse();
     if ($response->isClientError()) {
         $class = __NAMESPACE__ . '\\ClientFailureException';
     } else {
         $class = __NAMESPACE__ . '\\ServerFailureException';
     }
     $exception = new $class($response->getReasonPhrase(), null, $cause);
     if ($exception instanceof HttpException) {
         $statusCode = $response->getStatusCode();
         $httpMethod = $request->getMethod();
         $exception->setStatusCode($statusCode);
         $exception->setResponse($response);
         $exception->setRequest($request);
         if (isset(self::$descriptionMapping[$httpMethod][$statusCode])) {
             $exception->setDescription(self::$descriptionMapping[$httpMethod][$statusCode]);
         }
     }
     return $exception;
 }
Esempio n. 16
0
 /**
  * Handle a bad response coming back when getting token credentials.
  *
  * @param  BadResponseException $e
  * @return void
  * @throws CredentialsException
  */
 protected function handleTokenCredentialsBadResponse(BadResponseException $e)
 {
     $response = $e->getResponse();
     $body = $response->getBody();
     $statusCode = $response->getStatusCode();
     throw new CredentialsException("Received HTTP status code [{$statusCode}] with message \"{$body}\" when getting token credentials.");
 }
Esempio n. 17
0
 /**
  *
  * @param \Guzzle\Http\Message\Response $response            
  * @return \Guzzle\Http\Client
  */
 protected function getHttpClientMock(Response $response)
 {
     $client = $this->getMockBuilder('\\Guzzle\\Http\\Client')->setMethods(array('send'))->getMock();
     if ($response->isError()) {
         $request = $this->getMockBuilder('\\Guzzle\\Http\\Message\\Request')->disableOriginalConstructor()->getMock();
         $e = BadResponseException::factory($request, $response);
         $client->expects($this->any())->method('send')->will($this->throwException($e));
     } else {
         $client->expects($this->any())->method('send')->will($this->returnValue($response));
     }
     return $client;
 }
 /**
  * Default method that will throw exceptions if an unsuccessful response
  * is received.
  *
  * @param Event $event Received
  * @throws BadResponseException if the response is not successful
  */
 public static function onRequestError(Event $event)
 {
     $e = BadResponseException::factory($event['request'], $event['response']);
     $event['request']->dispatch('request.exception', array('request' => $event['request'], 'response' => $event['response'], 'exception' => $e));
     throw $e;
 }
Esempio n. 19
0
 private function handleBadResponseExceptions(BadResponseException $exception)
 {
     $response = $exception->getResponse();
     $json = $response->json();
     throw new RuntimeException(sprintf('Request to Dropbox failed: %s [%d]', $json['error'], $response->getStatusCode()));
 }
Esempio n. 20
0
 private function createGuzzleException($statusCode, $body = null)
 {
     return \Guzzle\Http\Exception\BadResponseException::factory(new \Guzzle\Http\Message\Request('GET', 'http://example.com/'), new \Guzzle\Http\Message\Response($statusCode, null, $body));
 }
 /**
  * @param BadResponseException $object
  *
  * @return string
  */
 public function getErrorMessage(BadResponseException $error)
 {
     return $error->getMessage();
 }
Esempio n. 22
0
 /**
  * @covers PusherService::handleException
  * @dataProvider exceptionDataProvider
  */
 public function testExceptionsAreThrownOnErrors($statusCode, $expectedException)
 {
     $method = new ReflectionMethod('ZfrPusher\\Service\\PusherService', 'handleException');
     $method->setAccessible(true);
     $exception = new BadResponseException();
     $exception->setResponse(new Response($statusCode));
     $this->setExpectedException($expectedException);
     $method->invoke($this->service, $exception);
 }
Esempio n. 23
0
 private function handleBadResponseExceptions(BadResponseException $exception)
 {
     $response = $exception->getResponse();
     $json = $response->json();
     $message = isset($json['error']['message']) ? $json['error']['message'] : $json['error'];
     throw new RuntimeException(sprintf('Request to Google Drive failed: %s [%d]', $message, $response->getStatusCode()));
 }
 /**
  * Default method that will throw exceptions if an unsuccessful response is received.
  *
  * @param Event $event Received
  * @throws BadResponseException if the response is not successful
  */
 public static function onRequestError(Event $event)
 {
     $e = BadResponseException::factory($event['request'], $event['response']);
     $event['request']->setState(self::STATE_ERROR, array('exception' => $e) + $event->toArray());
     throw $e;
 }
Esempio n. 25
0
 /**
  * Throw specific Pusher exceptions according to the status code
  *
  * @param  BadResponseException $exception
  * @throws Exception\UnauthorizedException
  * @throws Exception\ForbiddenException
  * @throws Exception\RuntimeException
  * @throws Exception\UnknownResourceException
  * @return void
  */
 protected function handleException(BadResponseException $exception)
 {
     $response = $exception->getResponse();
     if ($response->isSuccessful()) {
         return;
     }
     // Reason is injected into the body content, however we do not really want to output the whole
     // body content to the user, but rather only the real reason, which is typically the last line
     // of the body content
     $body = array_filter(explode(PHP_EOL, $response->getMessage()));
     $message = end($body);
     switch ($response->getStatusCode()) {
         case 400:
             throw new Exception\RuntimeException(sprintf('An error occurred while trying to handle your request. Reason: %s', $message), 400);
         case 401:
             throw new Exception\UnauthorizedException(sprintf('You are not authorized to perform this action. Reason: %s', $message), 401);
         case 403:
             throw new Exception\ForbiddenException(sprintf('You are not allowed to perform this action, your application may be disabled or you may have reached your message quota. Reason: %s', $message), 403);
         case 404:
             throw new Exception\UnknownResourceException(sprintf('Resource cannot be found, are you sure it exists? Reason: %s', $message), 404);
         default:
             throw new Exception\RuntimeException(sprintf('An unknown error occurred on Pusher side. Reason: %s', $message), $response->getStatusCode());
     }
 }
Esempio n. 26
0
 /**
  * Handle an error response exception / object
  * @param BadResponseException $exception
  * @return ErrorException $error_exception
  */
 protected function handleErrorResponse(BadResponseException $exception)
 {
     $response = Response::create($exception->getResponse());
     $errorException = new ErrorException('An error occurred on this request', 0, $exception);
     $errorException->setResponse($response);
     $contentType = $response->getHttpHeader('Content-Type');
     if (!empty($contentType)) {
         $errorClass = $this->getErrorDocumentClass($contentType);
         if (!is_null($errorClass)) {
             $errorDocument = $errorClass::createFromString($response->getBody());
             $errorException->setErrorDocument($errorDocument);
         }
     }
     return $errorException;
 }
Esempio n. 27
0
 protected function buildException(GuzzleEx\BadResponseException $exception)
 {
     $response = $exception->getResponse();
     $body = $response->getBody(true);
     $message = $body;
     $code = null;
     if ($response->isContentType('application/json')) {
         $data = @json_decode($body, true);
         $message = isset($data['message']) ? $data['message'] : '(no error message given)';
         if (isset($data['status'])) {
             $status = (int) $data['status'];
             $code = $status - (int) ($status / 1000) * 1000;
         }
     }
     switch ($response->getStatusCode()) {
         case 400:
             return new SymfonyEx\BadRequestHttpException($message, null, $code);
         case 401:
         case 403:
             return new SymfonyEx\AccessDeniedHttpException($message, null, $code);
         case 404:
             return new SymfonyEx\NotFoundHttpException($message, null, $code);
         case 405:
             return new SymfonyEx\MethodNotAllowedHttpException(array(), $message, null, $code);
         case 406:
             return new SymfonyEx\NotAcceptableHttpException($message, null, $code);
         case 409:
             return new SymfonyEx\ConflictHttpException($message, null, $code);
         case 415:
             return new SymfonyEx\UnsupportedMediaTypeHttpException($message, null, $code);
         case 500:
         case 503:
             return new SymfonyEx\ServiceUnavailableHttpException(null, $message, null, $code);
         default:
             return new SymfonyEx\HttpException(500, $message, null, array(), $code);
     }
 }