json_encode可以触发catch块吗? [英] Can json_encode trigger a catch block?

查看:76
本文介绍了json_encode可以触发catch块吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这可能是一个非常简单的问题,但我只是找不到任何信息.

This is probably a really simple question, but I just can't find any info on it.

我使用的系统会汇总来自各种来源的大量数据,然后将这些数据存储在数据库中.在大多数情况下,该系统可以正常运行,但有时会遇到一个问题,即数据可能具有系统不喜欢的笨拙的字符编码(例如,当数据使用另一种语言(例如法语)时).

I work with a system that aggregates a lot of data from various sources and then stores that data in a database. For the most part, the system works fine, but occasionally we get an issue where data can have awkward character encoding (for instance, when the data is in another language, like French) that our system doesn't like.

数据被传递到我们的处理服务器(我们使用Gearman),并且为了确保与源有关的所有信息都被传递,我们json_encode一个数组,其中包含我们需要的所有内容.我对您的问题是:如果我将json_encode包装在try/catch块中,导致"PHP警告:json_encode():参数中的UTF-8序列无效"消息的事件会触发catch块激活吗?

The data gets passed to our processing server (we use Gearman), and to ensure that all the info pertaining to source gets passed we json_encode an array with everything we need. My question to you is: if I wrap the json_encode in a try/catch block, will things that cause "PHP Warning: json_encode(): Invalid UTF-8 sequence in argument" messages trigger the catch block to activate?

谢谢!

推荐答案

否,但是您可以在函数中检查它的返回值,并在出现问题时引发异常.您还可以使用 json_last_error 来获取有关的详细信息错误

No but you can check it's return value in a function and throw an exception when something goes wrong. You can also use json_last_error to get details on the error

示例:

function my_json_encode($data) {
    if( json_encode($data) === false ) {
        throw new Exception( json_last_error() );
    }
}

try {
    my_json_encode($data);
}
catch(Exception $e ) {
    // do something
}

我确实很烦人,要获取实际的错误消息,您必须检查从json_last_error()返回的常量列表.过去,我曾使用switch/case语句来实现这一点,但是根据错误,您可能会引发不同的异常.

I do find it highly annoying that to get the actual error message you have to check a list of constants that is returned from json_last_error(). In the past I've used a switch / case statement to make that happen but you could throw different exceptions depending on the error.

这篇关于json_encode可以触发catch块吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆