如何在ZF2控制器中捕获异常? [英] How to catch exceptions in your ZF2 controllers?

查看:129
本文介绍了如何在ZF2控制器中捕获异常?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经使用 ZF 2.0.3 ZendSkeletonApplication c $ c>我无法在控制器中捕获异常。例如,如果我将以下代码放在 module / Application / src / Application / Controller / IndexController.php 中:



public function indexAction(){
echoBEFORE\\\
;

  
try {
throw new \Exception(我的异常);
} catch(异常$ e){
echo捕获异常$ e\\\
;
退出;
}

并访问我获得的页面:

  BEFORE 
发生错误
执行期间发生错误;请稍后再试。
附加信息:
异常

文件:

模块/应用程序/ src /应用程序/控制器/ IndexController.php:25

消息:

我的例外

ViewModel 启动并显示异常,有效阻止我捕获它。



如何捕获<$ c中的异常$ c> ZF2 控制器?

解决方案

您正在扔PHP的通用异常



  throw new \Exception(我的异常); 

但是您从当前命名空间捕获异常

 } catch(Exception $ e){

假设您的控制器位于 Application\Controller 中,您必须声明

 使用\Exception; 

您的课程以上将全局异常导入当前命名空间或

  


I've setup the ZendSkeletonApplication with ZF 2.0.3 and I am unable to catch exceptions in my controllers. For instance if I put the below piece of code in module/Application/src/Application/Controller/IndexController.php:

public function indexAction() {
    echo "BEFORE\n";
    try {
        throw new \Exception("My exception");
    } catch (Exception $e) {
        echo "Caught exception $e\n";
        exit;
    }

and access the page I get:

BEFORE
An error occurred
An error occurred during execution; please try again later.
Additional information:
Exception

File:

    module/Application/src/Application/Controller/IndexController.php:25

Message:

    My exception

the ViewModel kicks in and displays the exception, effectively preventing me from catching it.

How can I catch exceptions in ZF2 controllers?

解决方案

You are throwing PHP's generic Exception

throw new \Exception("My exception");

but you catch the Exception from the current namespace

} catch (Exception $e) {

Assuming your controller is in Application\Controller, you either have to declare

use \Exception;

above your class to import the global Exception into the current namespace or

} catch (\Exception $e) {

to catch PHP's global Exception.

这篇关于如何在ZF2控制器中捕获异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆