Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How handling error of JSON decode by try and catch

Tags:

People also ask

How do I fix JSON decode error?

JSONDecodeError: Extra data" occurs when we try to parse multiple objects without wrapping them in an array. To solve the error, wrap the JSON objects in an array or declare a new property that points to an array value that contains the objects.

How do you handle JSON parsing error?

The best way to catch invalid JSON parsing errors is to put the calls to JSON. parse() to a try/catch block.

Does Json_decode throw error?

json_decode returns null for invalid input, even though null is also a perfectly valid object for JSON to decode to—this function is completely unreliable unless you also call json_last_error every time you use it.

What happens if JSON parse fails?

If passed an invalid JSON value, the method will throw an error, which will get passed to the catch() function. You can handle the error in the catch function as you see fit. If you use local storage to get the value you're parsing, open your browser's console and clear the local storage as it sometimes glitches.


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

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 a new PHP programmer. Sorry, if something is wrong.