2017-09-28 71 views
0

在我的IndexController的indexAction,我想抛出和捕获异常,然后在catch块,我想要做的事,像这样:ZF3:抛出和捕获异常

namespace Application\Controller; 

use Zend\Mvc\Controller\AbstractActionController; 

class IndexController extends AbstractActionController { 
    public function indexAction() { 
     try { 
      throw new \Exception('My exception error messag.'); 
     } catch(Exception $e) { 
      echo '111'; 
      exit; 
     } 
    } 
} 

当异常是抛出,而不是打印“111”并停止,它会呈现“myproject/module/Application/src/view/error/index.phtml”的异常消息,引发“我的异常错误消息”。像下面的截图:

enter image description here

我在 “的myproject /配置/ development.config.php” 发现我有这样的事情:

return [ 
    'view_manager' => [ 
     'display_exceptions' => true, 
    ], 
]; 

我试图改变的是假的,我得到的输出:

enter image description here

这意味着它仍然显示错误/索引视图,但它只是不显示异常详情

我想要的仅仅是“111”的输出。

+0

也许我失去了一些东西,但是你抛出了异常,你问怎么阻止它显示? – Script47

+0

@ Script47 1-我抛出异常(这是可以的),2-然后捕获它,但不是打印111,它会呈现错误/索引! – evilReiko

+0

但是我不知道你在哪里告诉它打印111. – Script47

回答

1

答案是@Gordon here。我不会在这里删除这个问题和答案,因为这个问题和答案是关于ZF2的,而这个问题是关于ZF3的。

就像ZF2一样,问题在于命名空间。

try { 
    throw new \Exception('My exception error messag.'); 
} catch(\Exception $e){// <<< Use \Exception instead of Exception 
    echo 111; 
    exit; 
} 

或像戈登说,use \Exception;在文件的顶部,这样我们可以更换\异常有异常。