【问题标题】:How to correctly set up exception handler in Zend?如何在 Zend 中正确设置异常处理程序?
【发布时间】:2011-11-06 00:32:55
【问题描述】:

我正在尝试在 Zend (RESTful) 中为我的几个控制器重新定义异常处理程序。

这是我的一段代码:

abstract class RestController extends Zend_Rest_Controller
{
    public function init()
    {
        set_exception_handler(array($this, 'fault'));
    }

    public function fault($exception = null, $code = null)
    {
       echo $exception->getMessage();
    }
}

但由于某种原因,Zend 使用默认模板/错误处理,而我的 fault 函数没有执行。 顺便说一句,我正在使用module 架构。该控制器来自rest 模块。Zend 的默认错误处理程序来自default 模块。

【问题讨论】:

    标签: php zend-framework error-handling


    【解决方案1】:

    这是一个有趣的问题。目前我并不完全确定,所以我将对此进行一些研究,看看我想出了什么。现在有一些解决方法也不是太贫民窟。一种方法是创建一个抽象控制器,从该控制器扩展其余模块中的所有控制器。

    abstract class RestAbstractController extends Zend_Rest_Controller
    {
        final public function __call($methodName, $args)
        {
            throw new MyRestException("Method {$methodName} doesn't exist", 500);
        }
    }
    
    // the extends part here is optional
    class MyRestException extends Zend_Rest_Exception
    {
        public function fault($exception = null, $code = null)
        {
            echo $exception->getMessage() . ' ' . __CLASS__;
            exit;
        }
    }
    
    class RestController extends RestAbstractController
    {
        // method list
    }
    

    另外,我发现了这篇有趣的文章:http://zend-framework-community.634137.n4.nabble.com/Dealing-with-uncatched-exceptions-and-using-set-exception-handler-in-Zend-Framework-td1566606.html

    编辑:

    您需要在引导文件的某处添加以下内容:

    $this->_front->throwExceptions(true);
    $ex = new MyRestException();
    set_exception_handler(array($ex, 'fault'));
    

    那里的第一行应该有效地关闭 Zend 的异常处理,唯一缺少的是一个控制结构来确定当前请求是否针对您的 REST 服务。 注意 这必须放在 Bootstrap.php 文件中的原因是您在 init() 函数中对 set_exception_handler() 的调用从未到达,因为 Zend 框架首先抛出异常。将它放在引导文件中会抵消这一点。

    【讨论】:

    • 它只适用于错过的方法,但不会捕获用户生成的异常和mysql异常。应该有另一种方式..
    • 好的,明白了。好吧,看看我的编辑。我认为这应该是您的解决方案!
    • 谢谢。我也考虑过引导程序,但在这种情况下,我错过了 OOP 和控制器的所有优势。
    【解决方案2】:

    终于自己解决了问题:)

    来自Zend documentation

    Zend_Controller_Front::throwExceptions()

    通过给这个方法传递一个布尔值TRUE,可以告诉前面 控制器,而不是在响应中聚合异常 对象或使用错误处理程序插件,您宁愿处理它们 自己

    所以,正确的解决方案是这样的:

    abstract class RestController extends Zend_Rest_Controller
    {
        public function init()
        {
            $front = Zend_Controller_Front::getInstance();
            $front->throwExceptions(true);
    
            set_exception_handler(array($this, 'fault'));
        }
    
        public function fault($exception = null, $code = null)
        {
           echo $exception->getMessage();
        }
    }
    

    我们只需要添加

    $front = Zend_Controller_Front::getInstance();
    $front->throwExceptions(true);
    

    set_exception_handler 之前使其工作。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-05-10
      • 1970-01-01
      • 2010-11-16
      • 1970-01-01
      • 2013-09-22
      • 2011-09-05
      相关资源
      最近更新 更多