How handling error of json decode by try and catch

匿名 (未验证) 提交于 2019-12-03 08:46:08

问题:

I unable to handle json decode error.I mention my code below:-

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

I am new php programmer. Sorry, if something is wrong.

回答1:

Another way to handle json decode error:-

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


回答2:

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.



回答3:

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



易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!