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?

Ken J
  • 4,312
  • 12
  • 50
  • 86
  • 1
    Warnings are not exceptions, they are handled differently by default. See link below...... – rjdown Jan 14 '16 at 23:45
  • 1
    Possible duplicate of [Can I try/catch a warning?](http://stackoverflow.com/questions/1241728/can-i-try-catch-a-warning) – rjdown Jan 14 '16 at 23:45

2 Answers2

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();

Community
  • 1
  • 1
Chris Brewer
  • 108
  • 1
  • 6
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;
       }
    } 
}    
sal
  • 3,515
  • 1
  • 10
  • 21