Skip to content

Commit 547f84d

Browse files
committed
added logic to handle error responses
1 parent 079c214 commit 547f84d

File tree

1 file changed

+19
-12
lines changed

1 file changed

+19
-12
lines changed

lib/SparkPost/APIResource.php

Lines changed: 19 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,8 @@
33
use Ivory\HttpAdapter\HttpAdapterException;
44
use SparkPost\SparkPost;
55

6+
7+
68
/**
79
* @desc SDK interface for managing SparkPost API endpoints
810
*/
@@ -186,24 +188,29 @@ private function callResource( $action, $resourcePath=null, $options=[] ) {
186188
//make request
187189
try {
188190
$response = $this->sparkpost->httpAdapter->send($url, $action, $this->sparkpost->getHttpHeaders(), $body);
189-
return json_decode($response->getBody()->getContents(), true);
190-
}
191-
/*
192-
* Handles 4XX responses
193-
*/
194-
catch (HttpAdapterException $exception) {
195-
$response = $exception->getResponse();
191+
196192
$statusCode = $response->getStatusCode();
197-
if($statusCode === 404) {
198-
throw new \Exception('The specified resource does not exist', 404);
193+
194+
// Handle 4XX responses, 5XX responses will throw an HttpAdapterException
195+
if ($statusCode < 400) {
196+
return json_decode($response->getBody()->getContents(), true);
197+
} else {
198+
if ($statusCode === 404) {
199+
throw new APIResponseException('The specified resource does not exist', 404);
200+
}
201+
throw new APIResponseException('Received bad response from '.ucfirst($this->endpoint).' API: '. $statusCode );
199202
}
200-
throw new \Exception('Received bad response from '.ucfirst($this->endpoint).' API: '. $statusCode );
201203
}
204+
202205
/*
203-
* Handles 5XX Errors, Configuration Errors, and a catch all for other errors
206+
* Configuration Errors, and a catch all for other errors
204207
*/
205208
catch (\Exception $exception) {
206-
throw new \Exception('Unable to contact '.ucfirst($this->endpoint).' API: '. $exception->getMessage());
209+
if($exception instanceof APIResponseException) {
210+
throw $exception;
211+
}
212+
213+
throw new APIResponseException('Unable to contact '.ucfirst($this->endpoint).' API: '. $exception->getMessage());
207214
}
208215
}
209216

0 commit comments

Comments
 (0)