【问题标题】:Can json_encode trigger a catch block? [duplicate]json_encode 可以触发 catch 块吗? [复制]
【发布时间】:2012-09-04 14:38:41
【问题描述】:

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

我使用的系统会聚合来自各种来源的大量数据,然后将这些数据存储在数据库中。在大多数情况下,系统运行良好,但有时我们会遇到一个问题,即数据可能会出现我们系统不喜欢的尴尬字符编码(例如,当数据是另一种语言,如法语时)。

数据被传递到我们的处理服务器(我们使用 Gearman),为了确保与源有关的所有信息都被传递,我们使用我们需要的一切对数组进行 json_encode。我的问题是:如果我将 json_encode 包装在 try/catch 块中,导致“PHP 警告:json_encode(): Invalid UTF-8 sequence in argument”消息的事情会触发 catch 块激活吗?

谢谢!

【问题讨论】:

  • 我不认为json 抛出异常......
  • 你想问如果你这样做它是否会产生警告,或者它正在产生警告并且你已经尝试过?
  • 您可以尝试在调用前加上@ 来抑制错误并检查返回值。例如。 if (($str = @json_encode($foo)) !== FALSE) { ...do your stuff, encoding succeeded... }

标签: php json


【解决方案1】:

不,但您可以在函数中检查它的返回值,并在出现问题时抛出异常。您也可以使用json_last_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 语句来实现这一点,但您可以根据错误抛出不同的异常。

【讨论】:

  • 我不知道为什么我没有这样做。感谢您的帮助!
【解决方案2】:

不是本机,您需要设置一些自定义错误处理。

<?php

function exception_error_handler($errno, $errstr, $errfile, $errline)
{
    throw new ErrorException($errstr, $errno, 0, $errfile, $errline);
}

set_error_handler('exception_error_handler');

那么你可以这样做:

try
{
    json_encode(...);
}
catch (ErrorException $e)
{
    // do some thing with $e->getMessage()
}

但请记住,这将导致所有 PHP 错误引发异常,因此您应该根据需要对其进行微调。

【讨论】:

【解决方案3】:

您还可以根据错误输出错误或显示异常。就像下面的代码一样。

<?php


protected static $_messages = array(
    JSON_ERROR_NONE => 'No error has occurred',
    JSON_ERROR_DEPTH => 'The maximum stack depth has been exceeded',
    JSON_ERROR_STATE_MISMATCH => 'Invalid or malformed JSON',
    JSON_ERROR_CTRL_CHAR => 'Control character error, possibly incorrectly encoded',
    JSON_ERROR_SYNTAX => 'Syntax error',
    JSON_ERROR_UTF8 => 'Malformed UTF-8 characters, possibly incorrectly encoded'
);

public static function encode($value, $options = 0) {
    $result = json_encode($value, $options);

    if($result)  {
        return $result;
    }

    throw new RuntimeException(static::$_messages[json_last_error()]);
}

public static function decode($json, $assoc = false) {
    $result = json_decode($json, $assoc);

    if($result) {
        return $result;
    }

    throw new RuntimeException(static::$_messages[json_last_error()]);
}

【讨论】:

    【解决方案4】:

    从 PHP 7.3 开始,您可以使用 JSON_THROW_ON_ERROR 选项。在 PHP 5.5 中,他们将 json_encode 的错误返回值从 null 更改为 false。这是一个涵盖各种 PHP 版本的解决方案。

    function callJSONFunc($jsonFuncName, $args) {
        if (defined('JSON_THROW_ON_ERROR')) {
            $args[1] = $args || JSON_THROW_ON_ERROR;
        }
        $ret = call_user_func_array($jsonFuncName, $args);
        if (!defined('JSON_THROW_ON_ERROR')) {
            if ($ret === false || $ret === null) {
                throw new JSONException(json_last_error_msg());
            }
        }
        return $ret;
    }
    
    class JSONException extends Exception {}
    
    function decodeJSON() { return callJSONFunc('json_decode', func_get_args()); }
    function encodeJSON() { return callJSONFunc('json_encode', func_get_args()); }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-08-22
      • 2011-05-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-09-16
      • 1970-01-01
      相关资源
      最近更新 更多