mac解压错误22无效的参数_看看PHP 7.3新版本中的JSON错误处理

53265266d857d1724a0a9399d4b21f68.png

php中文网最新课程

每日17点准时技术干货分享

a817d40bf53329dd445f83074a76d012.png

c6cb29743306a42e31463a491176268d.gif

在目前稳定的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()

}

以上就是本文给大家汇总介绍的PHP 7.3新版本中的JSON错误处理,希望小伙伴们能够喜欢。

a9197582ac514211490dd6f6564565f7.gif

-END-

声明:本文选自「 php中文网 」,搜索「 phpcnnew 」即可关注!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值