简体   繁体   English

ZF3:抛出和捕获异常

[英]ZF3: Throwing and catching exception

In my IndexController indexAction, I'm trying to throw and catch exception, then in the catch block, I want to do something, like so:在我的 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;
        }
    }
}

When the exception is thrown, instead of printing "111" and stopping, it renders view "myproject/module/Application/src/view/error/index.phtml" with the exception message I've thrown "My exception error messag".当抛出异常时,它不会打印“111”并停止,而是呈现视图“myproject/module/Application/src/view/error/index.phtml”,其中包含我抛出的异常消息“我的异常错误消息”。 Like the following screenshot:像下面的截图:

在此处输入图片说明

I found out in "myproject/config/development.config.php" I have something like this:我在“myproject/config/development.config.php”中发现我有这样的东西:

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

I tried changing that to false, I got the output:我尝试将其更改为 false,我得到了输出:

在此处输入图片说明

Which means it's still showing the error/index view but it just doesn't display the exception details这意味着它仍然显示错误/索引视图,但它只是不显示异常详细信息

What I want is simply an output of "111".我想要的只是“111”的输出。

Answer is by @Gordon here .答案是 @Gordon在这里 I'll not delete this question and answer here since that question and answer were about ZF2 while this one is about ZF3.我不会在这里删除这个问题和答案,因为那个问题和答案是关于 ZF2 而这个是关于 ZF3 的。

Just like ZF2, the issue is to do with namespacing.就像 ZF2 一样,问题与命名空间有关。

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

or like Gordon said, use \\Exception;或者像戈登说的, use \\Exception; in top of file so we can replace \\Exception with Exception.在文件顶部,所以我们可以用 Exception 替换 \\Exception。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM