2017-09-05 75 views
0

我被困在我工作的一个错误记录片的工作,最终却演化成了以下内容:PHP尝试捕捉最后发出

$errorMsg = 'No Errors Detected'; 
try{ 
    nonexistentfunction();  //Basically something here will not work 
}catch(Exception $e){ 
    $errorMsg = 'Oh well, something went wrong'; 
}finally{ 
    $this->logger->log($errorMsg); 
} 

然而,每一次记录仪记录,提示“无检测到错误',而应该记录'哦,出错了',因为我抛出了一个异常(在这个例子中找不到方法,但是可能会发生任何异常)。

如何获取catch()块中的代码执行?它似乎并没有执行!

+0

您正在使用什么版本的PHP? – fubar

+0

你在使用命名空间吗?尝试'} catch(\ Exception $ e){' – ishegg

+1

@RahulBhatnagar尝试使用'throw new \ Exception(“Custom exception!”)''而不是'nonexistentfunction()' –

回答

3

如果你在PHP中调用一个未定义的函数,它会引发一个致命错误,而不是一个例外。

因此,您需要捕获Error类型的对象。或者,您可以捕获Throwable对象,从ErrorException类都可以扩展。

http://php.net/manual/en/language.errors.php7.php

<?php 

$errorMsg = 'No Errors Detected'; 

try { 
    nonexistentfunction(); 
} 
catch (Throwable $e) { 
    $errorMsg = 'Oh well, something went wrong'; 
} 
finally{ 
    $this->logger->log($errorMsg); 
} 
+0

谢谢,尽管我实际上并没有调用非存在的函数,但是这个答案让我更完整地理解了catch为什么不起作用,因此被标记为正确。 –