如果我有一个没有声明并导致500个错误的函数,并且这个函数是在try块中调用的,那么函数之前完成的插入会被回滚吗?
当我尝试下面的代码时,catch不会处理500错误。
DB::connection()->getPdo()->beginTransaction();
try
{
$helper = new Helper;
$helper->functionThatIsNotDeclared();
DB::connection()->getPdo()->commit();
}
catch( \Exception $e)
{
DB::connection()->getPdo()->rollBack();
}是否有正确处理500错误的方法?
非常感谢。
发布于 2014-05-07 11:10:57
PHP中的致命错误终止当前代码“堆栈”并直接跳转到关机处理程序,因此它们避免了try/catch块。您可以注册致命错误处理程序:
App::fatal(function() { DB::getPdo()->rollback(); });但是,如果在发生另一个致命错误时没有启动事务,则这可能不能很好地工作。
这里的一般建议是从整体上避免致命的错误。致命错误表示代码中的错误,而不是在应用程序中发生更“预期”错误的异常。
发布于 2014-05-07 09:31:19
您可以使用method_exists() - http://www.php.net/manual/en/function.method-exists.php检查PHP中是否存在方法。
您的代码应该如下所示:
DB::connection()->getPdo()->beginTransaction();
try
{
$helper = new Helper;
if(method_exists($helper, 'functionThatIsNotDeclared')) {
// The method exists, do something
} else {
// The method doesn't exist, do something else
}
DB::connection()->getPdo()->commit();
}
catch(Exception $e)
{
DB::connection()->getPdo()->rollBack();
}虽然我认为您得到错误的原因是因为您的catch() --我相信您的意思是键入catch(Exception $e)而不是catch( \Exception $e)。
https://stackoverflow.com/questions/23513532
复制相似问题