【问题标题】:ZF3: Throwing and catching exceptionZF3:抛出和捕获异常
【发布时间】:2018-03-09 21:34:22
【问题描述】:

在我的 IndexController indexAction 中,我试图抛出并捕获异常,然后在 catch 块中,我想做一些事情,如下所示:

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”以及我抛出的异常消息“我的异常错误消息”。像下面的截图:

我在“myproject/config/development.config.php”中发现我有这样的东西:

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

我尝试将其更改为 false,我得到了输出:

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

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

【问题讨论】:

  • 也许我遗漏了一些东西,但你正在抛出异常并且你在问如何阻止它显示?
  • @Script47 1- 我抛出异常(这没关系),2- 然后捕获它,但不是打印 111,而是呈现错误/索引!
  • 但我看不出你告诉它在哪里打印 111。
  • @Script47 很抱歉,我写问题时的错误,已修复。它在 catch 块中
  • 这似乎对我有用here

标签: php zend-framework exception-handling zend-framework3


【解决方案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;
}

或者像 Gordon 说的,use \Exception; 在文件顶部,所以我们可以用 Exception 替换 \Exception。

【讨论】:

    猜你喜欢
    • 2013-06-24
    • 2016-12-15
    • 1970-01-01
    • 1970-01-01
    • 2016-02-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-25
    相关资源
    最近更新 更多