-
-
Notifications
You must be signed in to change notification settings - Fork 11
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Invalid .json Syntax & Error Handling #2
Comments
First, is there any reason you can't fix the invalid JSON? That would be the proper way to address this issue. Without proper formatting the file just decodes to In any case, I think catching the exception would accomplish exactly what you want. By wrapping the config instantiation line in a try-catch block the end-user (you) can determine what to do when an exception occurs (i.e. show a pretty notice or echo back an error message). You can do this with with the following block of code: try {
// This is what we're going to try, if it fails and an exception is thrown the catch
// statement will be evaluated and attempt to catch a specific exception.
$config = new Config\Config('/path/to/app/my_config.json');
} catch (Config\Exceptions\InvalidFileException $exception) {
// Here we look for a specific exception being thrown and do something explicit
// like show some sort of pretty panel/notice or echo back an exception message.
echo 'Invalid configuration file detected.';
}
// As long as the exception is caught and you don't explicitly kill the execution in the
// catch section your code will continue to be parsed and the app will continue to run. Unfortunately as it stands the thrown exception does not contain a message. I will have to update it to be more informative and include a name of or path to the file which is invalid. For for a full explanation of PHP Exceptions check out this informative tutorial (specifically sections 3 and 4). Also see the PHP docs for additional info on Exceptions including the available Exception methods. |
I'm using this in a couple of WordPress plugins. It would be nice if it not throw an Exception if the file syntax is invalid. Example:
If
config.json
has invalid syntax, it throws a nasty exception.I'm not sure how I would address this, but maybe you could return an Exception() object if there is an error. I'm just brainstorming...
Better maybe better?:
Thank you,
Daniel
The text was updated successfully, but these errors were encountered: