Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Wrap non-JSON responses in json error response #63

Draft
wants to merge 1 commit into
base: v4.x
Choose a base branch
from
Draft
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 18 additions & 9 deletions src/GuzzleAdapter.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
namespace TraderInteractive\Api;

use ArrayObject;
use GuzzleHttp\Psr7\Utils;
use TraderInteractive\Util;
use GuzzleHttp\Client as GuzzleClient;
use GuzzleHttp\ClientInterface as GuzzleClientInterface;
Expand Down Expand Up @@ -74,17 +75,25 @@ public function end(string $endHandle) : ResponseInterface
foreach ($results as $handle => $response) {
try {
$contents = (string)$response->getBody();
if (trim($contents) !== '') {
json_decode($contents, true);
Util::ensure(
JSON_ERROR_NONE,
json_last_error(),
'\UnexpectedValueException',
[json_last_error_msg()]
);
if (trim($contents) === '') {
$this->responses[$handle] = $response;
continue;
}

$this->responses[$handle] = $response;
json_decode($contents, true);
if (json_last_error() === JSON_ERROR_NONE) {
$this->responses[$handle] = $response;
continue;
}

$errorBody = [
'error' => [
'message' => 'Original API response did not contain valid JSON: ' . json_last_error_msg(),
'originalResponse' => $contents,
],
];

$this->responses[$handle] = $response->withBody(Utils::streamFor(json_encode($errorBody)));
} catch (\Exception $e) {
$this->exceptions[$handle] = $e;
}
Expand Down
Loading