From c6a4c2882d89c6bcceeeccd319549611a5d1801b Mon Sep 17 00:00:00 2001 From: ArthurHoaro Date: Sun, 12 Mar 2017 16:09:34 +0100 Subject: [PATCH] Proper error if the conf file is invalid instead of fatal error MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Error: An error occurred while parsing configuration JSON file (data/config.json.php): error code #4 ➜ Syntax error Please check your JSON syntax (without PHP comment tags) using a JSON lint tool such as jsonlint.com. --- application/config/ConfigJson.php | 10 ++++++++-- application/config/ConfigManager.php | 6 +++++- tests/config/ConfigJsonTest.php | 2 +- 3 files changed, 14 insertions(+), 4 deletions(-) diff --git a/application/config/ConfigJson.php b/application/config/ConfigJson.php index 30908d9..9ef2ef5 100644 --- a/application/config/ConfigJson.php +++ b/application/config/ConfigJson.php @@ -21,8 +21,14 @@ class ConfigJson implements ConfigIO $data = str_replace(self::getPhpSuffix(), '', $data); $data = json_decode($data, true); if ($data === null) { - $error = json_last_error(); - throw new \Exception('An error occurred while parsing JSON file: error code #'. $error); + $errorCode = json_last_error(); + $error = 'An error occurred while parsing JSON configuration file ('. $filepath .'): error code #'; + $error .= $errorCode. '
' . json_last_error_msg() .''; + if ($errorCode === JSON_ERROR_SYNTAX) { + $error .= '
Please check your JSON syntax (without PHP comment tags) using a JSON lint tool such as '; + $error .= 'jsonlint.com.'; + } + throw new \Exception($error); } return $data; } diff --git a/application/config/ConfigManager.php b/application/config/ConfigManager.php index f209741..e98af8a 100644 --- a/application/config/ConfigManager.php +++ b/application/config/ConfigManager.php @@ -81,7 +81,11 @@ class ConfigManager */ protected function load() { - $this->loadedConfig = $this->configIO->read($this->getConfigFileExt()); + try { + $this->loadedConfig = $this->configIO->read($this->getConfigFileExt()); + } catch (\Exception $e) { + die($e->getMessage()); + } $this->setDefaultValues(); } diff --git a/tests/config/ConfigJsonTest.php b/tests/config/ConfigJsonTest.php index 3527f83..d237bc8 100644 --- a/tests/config/ConfigJsonTest.php +++ b/tests/config/ConfigJsonTest.php @@ -40,7 +40,7 @@ class ConfigJsonTest extends \PHPUnit_Framework_TestCase * Read a non existent config file -> empty array. * * @expectedException \Exception - * @expectedExceptionMessage An error occurred while parsing JSON file: error code #4 + * @expectedExceptionMessageRegExp /An error occurred while parsing JSON configuration file \([\w\/\.]+\): error code #4/ */ public function testReadInvalidJson() {