登录  /  注册
首页 > 头条 > 正文

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

无忌哥哥
发布: 2018-07-12 11:39:34
原创
3425人浏览过

背景

在目前稳定的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()
}
登录后复制
智能AI问答
PHP中文网智能助手能迅速回答你的编程问题,提供实时的代码和解决方案,帮助你解决各种难题。不仅如此,它还能提供编程资源和学习指导,帮助你快速提升编程技能。无论你是初学者还是专业人士,AI智能助手都能成为你的可靠助手,助力你在编程领域取得更大的成就。
来源:php中文网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
关于CSS思维导图的课件在哪? 课件
凡人来自于2024-04-16 10:10:18
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2024 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号