背景
在目前稳定的php v7.2中,如果你想确定json是无效的,你必须使用json_last_error()功能验证:
>>> json_decode("{");=> null>>> json_last_error();=> 4>>> json_last_error() === json_error_none=> false>>> json_last_error_msg()=> "syntax error"
例如,在larave这里检查以确保调用json编码不会导致错误:
// once we get the encrypted value we'll go ahead and base64_encode the input// vector and create the mac for the encrypted value so we can then verify// its authenticity. then, we'll json the data into the "payload" array.$json = json_encode(compact('iv', 'value', 'mac'));if (json_last_error() !== json_error_none) { throw new encryptexception('could not encrypt the data.');}return base64_encode($json);
我们至少可以确定如果json编码/解码有错误,但相比有点笨重,抛出一个异常,放出错误代码和错误信息。
虽然你已经选择了,捕获和处理json,另外让我们看看新的版本,我们可以用一个很好的方式!
在php 7.3错误标志的抛出
随着新的选项标志json_throw_on_error有可能改写这一块的代码使用try/catch。
也许类似下面的:
use jsonexception;try { $json = json_encode(compact('iv', 'value', 'mac'), json_throw_on_error); return base64_encode($json);} catch (jsonexception $e) { throw new encryptexception('could not encrypt the data.', 0, $e);}
我认为这一新风格是特别有用的用户代码,当你收到一些json数据而不是搜寻json_last_error()和匹配的选项,json编码和解码可以利用错误处理程序。
这个json_decode()功能有几个参数,并将看起来像php 7.3以下如果你想利用错误处理:
use jsonexception;try { return json_decode($jsonstring, $assoc = true, $depth = 512, json_throw_on_error);} catch (jsonexception $e) { // handle the json exception}// or even just let it bubble up.../** * decode a json string into an array * * @return array * @throws jsonexception */function decode($jsonstring) { return json_decode($jsonstring, $assoc = true, $depth = 512, json_throw_on_error);}
得到的错误代码和错误信息
以前你获取json错误代码和消息使用以下功能:
// error codejson_last_error();// human-friendly messagejson_last_error_msg();
如果你使用新的json_throw_on_error,这里是你如何使用代码和获取消息:
try { return json_decode($jsonstring, $assoc = true, $depth = 512, json_throw_on_error);} catch (jsonexception $e) { $e->getmessage(); // like json_last_error_msg() $e->getcode(); // like json_last_error()}