• 技术文章 >头条

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

    无忌哥哥无忌哥哥2018-07-12 11:39:34原创2300

    背景

    在目前稳定的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中文网,转载请注明出处,感谢您的尊重!如有疑问,请联系admin@php.cn处理
    上一篇:PHP7.3新特性:将迎来灵活的 heredoc 和 nowdoc语法结构 下一篇:软件测试经验分享以及8点建议
    大前端线上培训班

    相关文章推荐

    • 从未停止前进,PHP8.1带来了8个重要的新转变!• 就凭这三招,Vue 让其它框架俯首称臣!• 最新消息!雅虎Yahoo正式退出中国了!• 重大消息!微软终于将VS Code带入浏览器了!• 粗谈编程 为您解答疑惑

    全部评论我要评论

  • 取消发布评论发送
  • 1/1

    PHP中文网