How handling error of json decode by try and catch

前端 未结 4 1470
栀梦
栀梦 2021-02-12 16:20

I am unable to handle JSON decode errors. Here is my code:

try {
    $jsonData = file_get_contents($filePath) . \']\';
           


        
相关标签:
4条回答
  • 2021-02-12 16:34

    json_decode returns null when a error occurs, like no valid json or exceeded depth size. So basically you just check with if whether the jsondata you obtained is null or not. If it is, use json_last_error to see what went wrong, if not then continue with the script.

    $json_data = json_decode($source, true);
    
    if($json_data == null){
      echo json_last_error() . "<br>";
      echo $source; // good to check what the source was, to see where it went wrong
    }else{
      //continue with script
    }
    

    Something like that should work.

    0 讨论(0)
  • 2021-02-12 16:37

    Another way to handle json decode error:-

    if ($jsonObj === null && json_last_error() !== JSON_ERROR_NONE) {
       echo "json data is incorrect";
    }
    
    0 讨论(0)
  • 2021-02-12 16:40

    May be you can try, validating json_decode

    try {
      $jsonData = file_get_contents($filePath) . ']';
      $jsonObj  = json_decode($jsonData, true);
    
      if (is_null($jsonObj)) {
        throw ('Error');
      }
    } catch (Exception $e) {
      echo '{"result":"FALSE","message":"Caught exception: ' . 
        $e->getMessage() . ' ~' . $filePath . '"}';
    }
    

    Read this too

    0 讨论(0)
  • 2021-02-12 16:51

    Since PHP 7.3 one can use the JSON_THROW_ON_ERROR constant.

    try {
        $jsonObj = json_decode($jsonData, true, $depth=512, JSON_THROW_ON_ERROR);
    } catch (Exception $e) {
        // handle exception
    }
    

    More: https://www.php.net/manual/de/function.json-decode.php#refsect1-function.json-decode-changelog

    0 讨论(0)
提交回复
热议问题