RestApiResponse: give a helpful hint on JSON errors

This commit is contained in:
Thomas Gelf 2016-02-01 14:57:34 +01:00
parent e139f4349f
commit c6c8b75c74
1 changed files with 22 additions and 3 deletions

View File

@ -2,6 +2,8 @@
namespace Icinga\Module\Director\Core;
use Icinga\Exception\IcingaException;
class RestApiResponse
{
protected $errorMessage;
@ -69,19 +71,36 @@ class RestApiResponse
protected function parseJsonResult($json)
{
$result = @json_decode($json);
if ($result === false) {
return $this->setJsonError();
if ($result === null) {
$this->setJsonError();
throw new IcingaException('Parsing JSON result failed: ' . $this->errorMessage);
}
$this->results = $result->results; // TODO: Check if set
return $this;
}
// TODO: just return json_last_error_msg() for PHP >= 5.5.0
protected function setJsonError()
{
switch (json_last_error()) {
case JSON_ERROR_DEPTH:
$this->errorMessage = 'The maximum stack depth has been exceeded';
break;
case JSON_ERROR_CTRL_CHAR:
$this->errorMessage = 'Control character error, possibly incorrectly encoded';
break;
case JSON_ERROR_STATE_MISMATCH:
$this->errorMessage = 'Invalid or malformed JSON';
break;
case JSON_ERROR_SYNTAX:
$this->errorMessage = 'Syntax error';
break;
case JSON_ERROR_UTF8:
$this->errorMessage = 'Malformed UTF-8 characters, possibly incorrectly encoded';
break;
default:
$this->errorMessage = 'An unknown JSON decode error occured';
$this->errorMessage = 'An error occured when parsing a JSON string';
}
return $this;