首页 > 解决方案 > 为什么 PHP try...catch (Exception) 不能捕获 Yii2 应用程序中 inconv() 引发的异常?

问题描述

我有 PHP 代码(从 Yii2 应用程序运行):

    public static function convertNotes($notes) {
        if(is_null($notes)) {
            return $notes;
        }
        $tmp = 'Multibyte conversion error';
        try {
            $tmp = iconv('UTF-16LE', 'UTF-8', $notes); 
        } catch (Exception $ex) {
            $tmp = 'Multibyte conversion error: '+$ex->message;
        }
        return $tmp;
    }

代码尝试将 UTF16LE 字符串(来自数据库)转换为 UTF8 字符串。有时输入字符串不正确,它不是有效的 UTF16LE 字符串(字节序列)。在这种情况下会引发异常:

PHP Notice – yii\base\ErrorException
iconv(): Detected an incomplete multibyte character in input string 

那也行。但奇怪的是 - 即使我将 iconv() 全部包装到 try/catch 中,异常也不会被捕获并且无论如何都会跳到顶层未被捕获。异常处理有什么问题?

标签: phpexceptionyii2try-catch

解决方案


ErrorException必须从 Yii 框架中捕捉到:

try {
    $tmp = iconv('UTF-16LE', 'UTF-8', $notes); 
} catch (Exception $ex) {
    $tmp = 'Multibyte conversion error: '+$ex->message;
} catch (yii\base\ErrorException $ex) {
    $tmp = 'Multibyte conversion error (from Yii2): '.$ex->getName();
}

推荐阅读