Skip to content

Commit 44da511

Browse files
author
Apostolos Krionidis
committed
Created 'decodeValidJson' method that throws error when not correct JSON response
1 parent 8bbdd62 commit 44da511

File tree

1 file changed

+69
-1
lines changed

1 file changed

+69
-1
lines changed

src/Response/Response.php

Lines changed: 69 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -43,6 +43,7 @@ abstract class Response
4343
/**
4444
* Parse errors object, will copy any top members available at this
4545
* @param ResponseInterface $response
46+
* @throws \JsonException
4647
*/
4748
public function __construct(ResponseInterface $response)
4849
{
@@ -52,7 +53,7 @@ public function __construct(ResponseInterface $response)
5253
$response->getBody()->rewind();
5354
}
5455

55-
$body = json_decode($response->getBody()->getContents());
56+
$body = $this->decodeValidJson($response->getBody()->getContents());
5657

5758
if ($body) {
5859
$members = array_keys(get_object_vars($this));
@@ -65,6 +66,73 @@ public function __construct(ResponseInterface $response)
6566
}
6667
}
6768

69+
/**
70+
* @throws \JsonException
71+
*/
72+
protected function decodeValidJson(string $json)
73+
{
74+
$body = json_decode($json, false, 512, JSON_THROW_ON_ERROR);
75+
76+
// Check and throw exception in case of unhandled decode error
77+
$this->throwOnJsonLastError($body);
78+
79+
return $body;
80+
}
81+
82+
/**
83+
* @throws \JsonException
84+
*/
85+
private function throwOnJsonLastError($decoded)
86+
{
87+
$generalErrorMessage = 'Could not decode JSON!';
88+
89+
//Backwards compatability.
90+
if (!function_exists('json_last_error')) {
91+
92+
if ($decoded === false || $decoded === null) {
93+
throw new \JsonException($generalErrorMessage);
94+
}
95+
} else{
96+
97+
//Get the last JSON error.
98+
$jsonError = json_last_error();
99+
100+
//In some cases, this will happen.
101+
if (is_null($decoded) && $jsonError == JSON_ERROR_NONE) {
102+
throw new \JsonException($generalErrorMessage);
103+
}
104+
105+
//If an error exists.
106+
if ($jsonError != JSON_ERROR_NONE) {
107+
108+
//Use a switch statement to figure out the exact error.
109+
switch ($jsonError) {
110+
case JSON_ERROR_DEPTH:
111+
$error = 'Maximum depth exceeded!';
112+
break;
113+
case JSON_ERROR_STATE_MISMATCH:
114+
$error = 'Underflow or the modes mismatch!';
115+
break;
116+
case JSON_ERROR_CTRL_CHAR:
117+
$error = 'Unexpected control character found';
118+
break;
119+
case JSON_ERROR_SYNTAX:
120+
$error = 'Malformed JSON';
121+
break;
122+
case JSON_ERROR_UTF8:
123+
$error = 'Malformed UTF-8 characters found!';
124+
break;
125+
default:
126+
$error = 'Unknown error!';
127+
break;
128+
}
129+
130+
131+
throw new \JsonException(sprintf('%s %s', $generalErrorMessage, $error));
132+
}
133+
}
134+
}
135+
68136
/**
69137
* @return int
70138
*/

0 commit comments

Comments
 (0)