PHP尝试抓住最后一期

问题描述:

I got stuck working in an error logging piece that I'm working on, and ultimately it devolved into the following:

$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);
}

However, every time the logger logs the message 'No Errors Detected' while it should be logging 'Oh well, something went wrong' because I'm throwing an exception (method not found in this example, but any exception can occur).

How do I get the code in the catch() block to execute? It doesn't seem to execute at all!

我遇到了正在处理的错误记录片段,最终将其转移到以下内容中: p>

  $ errorMsg ='未检测到错误'; 
try {
 nonexistentfunction();  //基本上这里的东西不起作用
} catch(异常$ e){
 $ errorMsg ='哦,好吧,出了点问题'; 
}最后{
 $ this-> logger-> log(  $ errorMsg); 
} 
  code>  pre> 
 
 

然而,每当记录器记录消息“没有检测到错误”时它应该记录'哦,好吧,出了点问题 '因为我抛出一个异常(在这个例子中找不到方法,但是可能发生任何异常)。 p>

如何让catch()块中的代码执行? 它似乎根本没有执行! p> div>

If you call an undefined function in PHP, it'll throw a fatal error, not an exception.

You'd therefore need to catch an object of type Error. Alternatively, you can catch Throwable objects, from with both Error and Exception classes extend.

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);
}