2011-11-06 116 views
2

我想重新定义Zend(RESTful)中几个控制器的异常处理程序。如何在Zend中正确设置异常处理程序?

这是我的一段代码:

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功能didnt执行。 顺便说一句,我正在使用module架构。该控制器来自rest模块.. Zend的默认错误处理程序来自default模块。

回答

4

这是一个有趣的问题。我现在还不完全确定,所以我要研究这一点,看看我想出了什么。现在有一些解决方案也不是太贫民窟。一种方法是创建一个抽象控制器,从中扩展您的休息模块中的所有控制器。

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 Framework首先抛出了异常。将其放置在引导文件中会对此进行反驳。

+0

它只适用于错过的方法,但用户生成的异常和mysql异常不会被捕获。应该有另一种方式.. –

+0

好吧。以及检查我的编辑。我认为这应该是你的解决方案! –

+0

谢谢。我也想过bootstrap,但是在那种情况下,我错过了OOP和控制器的所有优点。 –

-1

终于解决了这个问题由我自己:)

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之前,使其工作。