Skip to content

Commit

Permalink
SC-278: add more data to API Exceptions
Browse files Browse the repository at this point in the history
  • Loading branch information
timager authored and Timofey Geraymovich committed Sep 4, 2024
1 parent 4d51b1c commit b4682b0
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 13 deletions.
3 changes: 2 additions & 1 deletion composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,8 @@
"guzzlehttp/guzzle": "~6.1",
"psr/http-message": "~1.0",
"ext-simplexml": "*",
"ext-dom": "*"
"ext-dom": "*",
"ext-json": "*"
},
"require-dev": {
"php": "<8.0",
Expand Down
27 changes: 15 additions & 12 deletions src/RocketLabs/SellerCenterSdk/Core/Response/Factory.php
Original file line number Diff line number Diff line change
Expand Up @@ -15,19 +15,21 @@ class Factory
/**
* @param HttpResponseInterface $httpResponse
* @param string $class class name
* @return GenericResponse
* @return AbstractResponse
*/
public function buildResponse(HttpResponseInterface $httpResponse, $class = GenericResponse::class)
{
if ($httpResponse->getStatusCode() !== self::HTTP_CODE_200) {
throw new ApiException(ApiException::UNEXPECTED_RESPONSE, $httpResponse->getStatusCode());
throw new ApiException(ApiException::UNEXPECTED_RESPONSE.sprintf(
": [code %s] %s",
$httpResponse->getStatusCode(),
$httpResponse->getBody()
),
$httpResponse->getStatusCode()
);
}

$decodedResponse = $this->decodeJsonResponse((string)$httpResponse->getBody());

if ($decodedResponse === null) {
throw new ApiException(ApiException::INVALID_RESPONSE_BODY, $httpResponse->getStatusCode());
}
$decodedResponse = $this->decodeJsonResponse($httpResponse);

$envelope = key($decodedResponse);

Expand All @@ -39,19 +41,20 @@ public function buildResponse(HttpResponseInterface $httpResponse, $class = Gene
}

/**
* @param string $apiResponseBody
* @param HttpResponseInterface $response
*
* @return array|null
* @return array
*/
protected function decodeJsonResponse($apiResponseBody)
protected function decodeJsonResponse($response)
{
$jsonDecoded = json_decode($apiResponseBody, true);
$body = (string)$response->getBody();
$jsonDecoded = json_decode($body, true);

// Only array could be valid api response
if (is_array($jsonDecoded)) {
return $jsonDecoded;
}

return null;
throw new ApiException(sprintf("%s: %s", ApiException::INVALID_RESPONSE_BODY, $body), $response->getStatusCode());
}
}

0 comments on commit b4682b0

Please sign in to comment.