没有不值得去解决的问题,也没有不值得去学习的技术!

Troubleshooting the “Malformed UTF-8 characters, possibly incorrectly encoded” Error in Yii 2.0

Printing the output of $e->getMessage() reveals that it contains garbled characters.

1. Error reported in Yii 2.0: Malformed UTF-8 characters, possibly incorrectly encoded.

JSON
{
    "name": "Exception",
    "message": "Malformed UTF-8 characters, possibly incorrectly encoded.",
    "code": 5,
    "type": "yii\\base\\InvalidArgumentException",
    "file": "E:\\wwwroot\\pcs-api-feature-base-3.0\\vendor\\yiisoft\\yii2\\helpers\\BaseJson.php",
    "line": 133,
    "stack-trace": [
        "#0 E:\\wwwroot\\pcs-api-feature-base-3.0\\vendor\\yiisoft\\yii2\\helpers\\BaseJson.php(67): yii\\helpers\\BaseJson::handleJsonError(5)",
        "#1 E:\\wwwroot\\pcs-api-feature-base-3.0\\vendor\\yiisoft\\yii2\\web\\JsonResponseFormatter.php(119): yii\\helpers\\BaseJson::encode('SQLSTATE[HY000]...', 320)",
        "#2 E:\\wwwroot\\pcs-api-feature-base-3.0\\vendor\\yiisoft\\yii2\\web\\JsonResponseFormatter.php(104): yii\\web\\JsonResponseFormatter->formatJson(Object(yii\\web\\Response))",
        "#3 E:\\wwwroot\\pcs-api-feature-base-3.0\\vendor\\yiisoft\\yii2\\web\\Response.php(1070): yii\\web\\JsonResponseFormatter->format(Object(yii\\web\\Response))",
        "#4 E:\\wwwroot\\pcs-api-feature-base-3.0\\vendor\\yiisoft\\yii2\\web\\Response.php(337): yii\\web\\Response->prepare()",
        "#5 E:\\wwwroot\\pcs-api-feature-base-3.0\\vendor\\yiisoft\\yii2\\base\\Application.php(392): yii\\web\\Response->send()",
        "#6 E:\\wwwroot\\pcs-api-feature-base-3.0\\api\\web\\index.php(17): yii\\base\\Application->run()",
        "#7 {main}"
    ]
}

2. The code is as follows

PHP
<?php
 
namespace api\rests\check_status;
 
use Yii;
use yii\web\HttpException;
use yii\base\Exception;
use yii\data\ActiveDataProvider;
use yii\data\DataFilter;
 
class IndexAction extends \yii\rest\IndexAction
{
    /**
     * @return int|string|ActiveDataProvider|DataFilter|null
     */
    public function run()
    {
        try {
            Yii::$app->db->open();
            if (!Yii::$app->redis->ping()){
                throw new HttpException(500, 'Redis is unavailable.');
            } elseif (!Yii::$app->db->getIsActive()){
                throw new HttpException(500, 'Database is unavailable.');
            } else {
                return 200;
            }
        } catch (Exception $e) {
            $res = Yii::$app->response;
            $res->statusCode = 500;
            return $e->getMessage();
        }
    }
}
 

3. Printing the output of $e->getMessage() reveals that it contains garbled characters. See Figure 1

Printing the output of $e->getMessage() reveals that it contains garbled characters.
Figure 1
Plaintext
SQLSTATE[HY000] [2002] php_network_getaddresses: getaddrinfo failed: ��֪��������������

4. Edit the code, mb_convert_encoding — Convert character encoding. The response status code is 500, and the response body is: “SQLSTATE[HY000] [2002] php_network_getaddresses: getaddrinfo failed: Unknown host. “. See Figure 2

Edit the code, mb_convert_encoding — Convert character encoding. The response status code is 500, and the response body is: "SQLSTATE[HY000] [2002] php_network_getaddresses: getaddrinfo failed: Unknown host. ".
Figure 2
PHP
<?php
 
namespace api\rests\check_status;
 
use Yii;
use yii\web\HttpException;
use yii\base\Exception;
use yii\data\ActiveDataProvider;
use yii\data\DataFilter;
 
class IndexAction extends \yii\rest\IndexAction
{
    /**
     * @return array|false|int|string|string[]|ActiveDataProvider|DataFilter|null
     */
    public function run()
    {
        try {
            Yii::$app->db->open();
            if (!Yii::$app->redis->ping()){
                throw new HttpException(500, 'Redis is unavailable.');
            } elseif (!Yii::$app->db->getIsActive()){
                throw new HttpException(500, 'Database is unavailable.');
            } else {
                return 200;
            }
        } catch (Exception $e) {
            Yii::$app->response->statusCode = 500;
            $message = mb_convert_encoding($e->getMessage(), "UTF-8", ["UTF-8", "GBK", "GB2312", "BIG5"]);
            return $message;
        }
    }
}

5. I initially speculate that “Unknown host” is returned by the Windows 10 system. It is not closely related to whether the text is Chinese, but rather to the encoding of the Chinese characters themselves. Because when the message is “Failed to open redis DB connection (tcp://localhost:63799, database=57): 10061 – No connection could be made because the target machine actively refused it.\r\n”, it runs normally even without converting the character encoding.

关于作者 · 持续学习与技术实践

我是一名拥有 15 年以上开发经验的技术从业者,自 2013 年起持续运营个人技术博客,记录工作与个人项目中遇到的真实问题,以及解决问题过程中的探索、实践和思考。

除了技术写作,我也在持续开发和维护自己的独立项目,探索新技术和新工具在实际场景中的应用。我始终相信,没有不值得去解决的问题,也没有不值得去学习的技术。

如果这篇文章对你有所帮助,欢迎浏览博客中的其他文章,也欢迎交流技术经验与想法。

关于我  ·  GitHub  ·  邮件联系