【发布时间】:2011-10-10 12:26:21
【问题描述】:
我有一个 try-catch 块,它遍历一组记录,如下所示:
try {
foreach ( $json['location'] as $records ) {
$location = DnaExtractionTable::getInstance()->find($records['id']);
$location->setName($records['name']);
$location->setLatitude($records['latitude']);
$location->setLongitude($records['longitude']);
$location->setCountryId($records['country_id']);
$location->setRegionId($records['region_id']);
$location->setIslandId($records['island_id']);
$location->setRemarks($records['remarks']);
$location->save();
}
}
catch (Exception $e) {
...
}
我可以捕获每个抛出的异常并继续没有问题。但我也试图“捕捉”错误,例如当$records 数组中不存在索引时。
有可能做到吗?我该怎么做?我一直在玩set_X_handler 函数但没有成功。
更新 1:
根据 cmets 和答案的建议,我决定实现一个全局错误函数:
function exceptions_error_handler($severity, $message, $filename, $lineno) {
if (error_reporting() == 0) {
return;
}
if (error_reporting() & $severity) {
throw new ErrorException($message, 0, $severity, $filename, $lineno);
}
}
set_error_handler('exceptions_error_handler');
但即使我尝试强制出错,代码也不会执行。由于我正在使用 Symfony 进行开发,是否有声明该功能的地方? Symfony 是否会禁用或影响 set_error_handler 函数?
更新 2:
Symfony 肯定在搞乱我的错误和异常处理程序。
打开调试模式似乎激活了一个覆盖错误报告的 Symfony 自定义异常处理程序。
虽然我的try-catch 块配置为捕获一般Exception 对象,但关闭调试模式似乎绕过了某些异常。真是奇怪的行为。
谢谢!
【问题讨论】:
-
我已经更新了问题,因为我已经看到了这些解决方案并且没有解决我的问题
-
你能验证为什么它不起作用吗? error_reporting 是否关闭?是否每次都会调用 exceptions_error_handler?
-
我的错。 Symfony 正在生产模式下执行。但是现在我已经把它变成了调试模式,Symfony 似乎正在实现它自己的错误处理机制来覆盖我的自定义函数。
标签: php exception error-handling symfony-1.4