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; namespace Icinga\Module\Director\Core;
use Icinga\Exception\IcingaException;
class RestApiResponse class RestApiResponse
{ {
protected $errorMessage; protected $errorMessage;
@ -69,19 +71,36 @@ class RestApiResponse
protected function parseJsonResult($json) protected function parseJsonResult($json)
{ {
$result = @json_decode($json); $result = @json_decode($json);
if ($result === false) { if ($result === null) {
return $this->setJsonError(); $this->setJsonError();
throw new IcingaException('Parsing JSON result failed: ' . $this->errorMessage);
} }
$this->results = $result->results; // TODO: Check if set $this->results = $result->results; // TODO: Check if set
return $this; return $this;
} }
// TODO: just return json_last_error_msg() for PHP >= 5.5.0
protected function setJsonError() protected function setJsonError()
{ {
switch (json_last_error()) { 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: default:
$this->errorMessage = 'An unknown JSON decode error occured'; $this->errorMessage = 'An error occured when parsing a JSON string';
} }
return $this; return $this;