A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© 不二晨 金牌黑马   /  2019-3-1 09:15  /  1034 人查看  /  1 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

[size=1.875]背景
[size=1.875]在目前稳定的PHP V7.2中,如果你想确定JSON是无效的,你必须使用json_last_error()功能验证:
1
2
3
4
5
6
7
8
>>> json_decode("{");
=> null
>>> json_last_error();
=> 4
>>> json_last_error() === JSON_ERROR_NONE
=> false
>>> json_last_error_msg()
=> "Syntax error"

例如,在Larave这里检查以确保调用JSON编码不会导致错误:

1
2
3
4
5
6
7
8
// 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。

也许类似下面的:

1
2
3
4
5
6
7
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以下如果你想利用错误处理:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
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);
}

[size=1.875]得到的错误代码和错误信息
[size=1.875]以前你获取JSON错误代码和消息使用以下功能:
1
2
3
4
// Error code
json_last_error();
// Human-friendly message
json_last_error_msg();

如果你使用新的JSON_THROW_ON_ERROR,这里是你如何使用代码和获取消息:

1
2
3
4
5
6
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()
}


1 个回复

倒序浏览
奈斯,感谢分享
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马