Skip to content

Commit d4a7da0

Browse files
committed
Wrap non-JSON responses in json error response
1 parent e55b7cc commit d4a7da0

File tree

1 file changed

+18
-9
lines changed

1 file changed

+18
-9
lines changed

src/GuzzleAdapter.php

Lines changed: 18 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
namespace TraderInteractive\Api;
44

55
use ArrayObject;
6+
use GuzzleHttp\Psr7\Utils;
67
use TraderInteractive\Util;
78
use GuzzleHttp\Client as GuzzleClient;
89
use GuzzleHttp\ClientInterface as GuzzleClientInterface;
@@ -74,17 +75,25 @@ public function end(string $endHandle) : ResponseInterface
7475
foreach ($results as $handle => $response) {
7576
try {
7677
$contents = (string)$response->getBody();
77-
if (trim($contents) !== '') {
78-
json_decode($contents, true);
79-
Util::ensure(
80-
JSON_ERROR_NONE,
81-
json_last_error(),
82-
'\UnexpectedValueException',
83-
[json_last_error_msg()]
84-
);
78+
if (trim($contents) === '') {
79+
$this->responses[$handle] = $response;
80+
continue;
8581
}
8682

87-
$this->responses[$handle] = $response;
83+
json_decode($contents, true);
84+
if (json_last_error() === JSON_ERROR_NONE) {
85+
$this->responses[$handle] = $response;
86+
continue;
87+
}
88+
89+
$errorBody = [
90+
'error' => [
91+
'message' => 'Original API response did not contain valid JSON: ' . json_last_error_msg(),
92+
'originalResponse' => $contents,
93+
],
94+
];
95+
96+
$this->responses[$handle] = $response->withBody(Utils::streamFor(json_encode($errorBody)));
8897
} catch (\Exception $e) {
8998
$this->exceptions[$handle] = $e;
9099
}

0 commit comments

Comments
 (0)