【问题标题】:How handling error of JSON decode by try and catch如何通过 try 和 catch 处理 JSON decode 的错误
【发布时间】:2015-07-23 05:35:02
【问题描述】:

我无法处理 JSON 解码错误。这是我的代码:

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

我是一名新的 PHP 程序员。抱歉,如果有问题。

【问题讨论】:

标签: php


【解决方案1】:

另一种处理json解码错误的方法:-

if ($jsonObj === null && json_last_error() !== JSON_ERROR_NONE) {
   echo "json data is incorrect";
}

【讨论】:

    【解决方案2】:

    从 PHP 7.3 开始可以使用JSON_THROW_ON_ERROR 常量。

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

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

    【讨论】:

      【解决方案3】:

      也许你可以试试,验证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

      【讨论】:

      • 既然可以检查$jsonObj === null,为什么还要打电话给is_null()?
      • 比较 is_null() 和 === null 没有区别。我会说这只是一种偏好。查看这个stackoverflow.com/questions/8228837/is-nullx-vs-x-null-in-php 了解更多信息。
      • @MilenGardev 您链接到的答案并未说明“没有区别”。它实际上列出了差异,因此选择哪一个取决于场景。如果您不需要回调,那么与具有额外开销的函数相比,不使用性能更高的=== null 是没有意义的。
      【解决方案4】:

      json_decode 在发生错误时返回 null,例如没有有效的 json 或超出深度大小。所以基本上你只需检查你获得的 jsondata 是否为空。如果是,请使用 json_last_error 看看出了什么问题,如果不是,则继续执行脚本。

      $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
      }
      

      类似的东西应该可以工作。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2020-08-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-11-20
        • 2019-09-10
        • 1970-01-01
        相关资源
        最近更新 更多