From c6c8b75c741b80411146a8b0c3bd82ff1389ec2c Mon Sep 17 00:00:00 2001 From: Thomas Gelf Date: Mon, 1 Feb 2016 14:57:34 +0100 Subject: [PATCH] RestApiResponse: give a helpful hint on JSON errors --- library/Director/Core/RestApiResponse.php | 25 ++++++++++++++++++++--- 1 file changed, 22 insertions(+), 3 deletions(-) diff --git a/library/Director/Core/RestApiResponse.php b/library/Director/Core/RestApiResponse.php index eb7b771b..b5a00329 100644 --- a/library/Director/Core/RestApiResponse.php +++ b/library/Director/Core/RestApiResponse.php @@ -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;