php - 为什么 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 中,异常也不会被捕获并且无论如何都会跳到顶层未被捕获。异常处理有什么问题?
解决方案
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();
}
推荐阅读
- swift - 在 SwiftUI 类中调用包装的 UIViewController 函数时获得 nil
- android - Android Studio 既不是模拟器也不是真实设备工作
- javascript - JavaScript 中的逻辑运算符 && 和 C# 等效
- python - Python csv模块读取特定行
- asp.net - 在 IIS 8 中更改默认页面时出现错误 302
- mysql - 将 MySQL 输出从 SELECT 查询转换为 UPDATE 查询
- python - Pandas Groupby 占总数的百分比
- python - 如何使用 Python OpenCV 在 QGIS 中捕获地图?
- android - Jetpack 导航无法导航到其他目的地
- angular - 使用 php 的 Angular 7 http post 失败并出现 404