0

I have a simple function within a class. I'm trying to get increase exception handling by using try/catch. My problem is that the returning from the try/catch is not stopping processing in the function. Here's my code:

class Config {

public static $configarray;

function setConfig($json_path) {
    try {
        file_get_contents($config_file);
    } catch (Exception $e) {
        die("Config File not found");
        return null;
    }
    $json = file_get_contents($json_path);
    try {
        json_decode($json,TRUE);
    } catch (Exception $e) {
        die("Invalid Config file. Check your JSON.");
        return null;
    }
    self::$configarray = json_decode($json,TRUE);
}    

} // End of Class

When I run

Config->setConfig('test.json')

I get these errors:

PHP Warning:  file_get_contents(test.json): failed to open stream: No such file or directory in /Config.php on line 30
PHP Warning:  file_get_contents(test.json): failed to open stream: No such file or directory in /Config.php on line 36

I ALWAYS want to print "Config File Not Found" if the file is not found. How can I catch the exception and prevent further processing in the function?

2
  • 1
    Warnings are not exceptions, they are handled differently by default. See link below...... Commented Jan 14, 2016 at 23:45
  • 1
    Possible duplicate of Can I try/catch a warning? Commented Jan 14, 2016 at 23:45

2 Answers 2

1

See How can I handle the warning of file_get_contents() function in PHP? for details on how to handle exceptions from the function: file_get_contents();

Sign up to request clarification or add additional context in comments.

Comments

0

Per the documentation on file_get_contents(), the function returns the read data or FALSE on failure, so there in your case there isn't an exception to catch, thus that code path is not executed. In fact you receive the WARNING printed, but none of your code's error messages.

To handle the case properly, the suggestion from Chris is correct, and the code would look something like the following. Similarly, you need to protect your json-decoding logic.

function setConfig($json_path) {
    $data = file_get_contents($config_file);
    if ( $data === FALSE ) {
       die("Could not read the Config File content");
       return null;
    }
    self::$configarray = null;
    $json = file_get_contents($json_path);
    if ( $json !== FALSE ) {
       try {
           self::$configarray = json_decode($json,TRUE);

       } catch (Exception $e) {
           die("Invalid Config file. Check your JSON.");
           return null;
       }
    } 
}    

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.