看看PHP 7.3新版本中的JSON错误处理

无忌哥哥
无忌哥哥原创
2018-07-12 11:39:343006浏览

背景

在目前稳定的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 code
json_last_error();
// Human-friendly message
json_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()
}
声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn核实处理。