From 5308ff8fbdb956a7b1971508e09749e982f8cb28 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Pawe=C5=82=20Krzaczkowski?= Date: Wed, 13 Jan 2016 11:18:31 +0100 Subject: [PATCH] handle timeout errors --- src/Client.php | 9 ++++++++ src/Exception/CustomerioException.php | 4 ++++ tests/ClientTest.php | 33 +++++++++++++++++++++++++++ 3 files changed, 46 insertions(+) diff --git a/src/Client.php b/src/Client.php index 45b85e8..009f219 100644 --- a/src/Client.php +++ b/src/Client.php @@ -10,6 +10,7 @@ use GuzzleHttp\Command\Guzzle\GuzzleClient; use GuzzleHttp\Event\CompleteEvent; use GuzzleHttp\Exception\ParseException; +use GuzzleHttp\Message\Response; use GuzzleHttp\Subscriber\Retry\RetrySubscriber; /** @@ -151,6 +152,14 @@ private function handleErrors() // Stop other events from firing when you override 401 responses $e->stopPropagation(); + + if (!$e->getResponse()) { + $response = new Response(502, [], null); + $response->setReasonPhrase($e->getException()->getMessage()); + $e = CustomerioException::factory($e->getRequest(), $response, $e); + throw $e; + } + if ($e->getResponse()->getStatusCode() >= 400 && $e->getResponse()->getStatusCode() < 600) { $e = CustomerioException::factory($e->getRequest(), $e->getResponse(), $e); throw $e; diff --git a/src/Exception/CustomerioException.php b/src/Exception/CustomerioException.php index 894ffc4..ea916f1 100644 --- a/src/Exception/CustomerioException.php +++ b/src/Exception/CustomerioException.php @@ -91,6 +91,10 @@ public static function factory(RequestInterface $request, ResponseInterface $res */ private static function isValidError($responseBody) { + if (!$responseBody || !is_array($responseBody)) { + return false; + } + if (array_key_exists('meta', $responseBody) && array_key_exists('error', $responseBody['meta']) ) { diff --git a/tests/ClientTest.php b/tests/ClientTest.php index b9e5153..e435019 100644 --- a/tests/ClientTest.php +++ b/tests/ClientTest.php @@ -6,7 +6,10 @@ use Customerio\Exception\ServerErrorResponseException; use GuzzleHttp\Client; use GuzzleHttp\Command\Guzzle\Description; +use GuzzleHttp\Exception\ConnectException; +use GuzzleHttp\Message\Request; use GuzzleHttp\Subscriber\History; +use GuzzleHttp\Subscriber\Mock; /** * Class ClientTest @@ -120,4 +123,34 @@ public function testUnsuccessfulResponse() $this->assertSame($e->getResponse()->getStatusCode(), 404); } } + + /** + * @expectedException \Customerio\Exception\CustomerioException + */ + public function testTimeoutResponse() + { + $history = new History(); + + $config['api_key'] = 'key'; + $config['site_id'] = 'site_id'; + + $client = new \Customerio\Client($config); + $httpClient = $client->getHttpClient(); + + $mock = new Mock(); + $mock->addException( + new ConnectException( + 'addCustomer', + new Request('post', '/') + ) + ); + + $httpClient->getEmitter()->attach($mock); + $httpClient->getEmitter()->attach($history); + + $client->addCustomer([ + 'id' => 45, + 'email' => 'test@example.com' + ]); + } }