douri4459
douri4459
2017-09-05 05:12

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!

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

1条回答

  • doutou6803 doutou6803 4年前

    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);
    }
    
    点赞 评论 复制链接分享

为你推荐