Browse Source

Show specific error message in exception if json_decode() fails.

Added json_last_error_msg() as fallback as it's not available in PHP 5.4 and below.
ADmad 11 years ago
parent
commit
c83a192ba5

+ 13 - 2
src/Core/Configure/Engine/JsonConfig.php

@@ -66,8 +66,19 @@ class JsonConfig implements ConfigEngineInterface
         $file = $this->_getFilePath($key, true);
 
         $values = json_decode(file_get_contents($file), true);
-        if (!is_array($values) || json_last_error() !== JSON_ERROR_NONE) {
-            throw new Exception(sprintf('Error parsing JSON string fetched from config file %s', $file));
+        if (json_last_error() !== JSON_ERROR_NONE) {
+            throw new Exception(sprintf(
+                "Error parsing JSON string fetched from config file \"%s.json\": %s",
+                $key,
+                json_last_error_msg()
+            ));
+        }
+        if (!is_array($values)) {
+            throw new Exception(sprintf(
+                'Decoding JSON config file "%s.json" did not return any array',
+                $key,
+                json_last_error_msg()
+            ));
         }
         return $values;
     }

+ 21 - 0
src/basics.php

@@ -334,3 +334,24 @@ if (!function_exists('__dxn')) {
     }
 
 }
+
+if (!function_exists('json_last_error_msg')) {
+    /**
+     * Provides the fallback implementation of json_last_error_msg() available in PHP 5.5 and above.
+     *
+     * @return string Error message.
+     */
+    function json_last_error_msg() {
+        static $errors = array(
+            JSON_ERROR_NONE => '',
+            JSON_ERROR_DEPTH => 'Maximum stack depth exceeded',
+            JSON_ERROR_STATE_MISMATCH => 'Invalid or malformed JSON',
+            JSON_ERROR_CTRL_CHAR => 'Control character error, possibly incorrectly encoded',
+            JSON_ERROR_SYNTAX => 'Syntax error',
+            JSON_ERROR_UTF8 => 'Malformed UTF-8 characters, possibly incorrectly encoded'
+        );
+        $error = json_last_error();
+        return array_key_exists($error, $errors) ? $errors[$error] : "Unknown error ({$error})";
+    }
+
+}

+ 2 - 0
tests/TestCase/Core/Configure/Engine/JsonConfigTest.php

@@ -98,6 +98,7 @@ class JsonConfigTest extends TestCase
      * Test reading an empty file.
      *
      * @expectedException \Cake\Core\Exception\Exception
+     * @expcetedExceptionMessage Decoding JSON config file "empty.json" did not return any array
      * @return void
      */
     public function testReadEmptyFile()
@@ -110,6 +111,7 @@ class JsonConfigTest extends TestCase
      * Test an exception is thrown by reading files that contain invalid JSON.
      *
      * @expectedException \Cake\Core\Exception\Exception
+     * @expectedExceptionMessage Error parsing JSON string fetched from config file "invalid.json"
      * @return void
      */
     public function testReadWithInvalidJson()