我正试图在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
模块。
这是一个有趣的问题。我现在还不完全确定,所以我要研究一下这个,看看我能想出什么。目前,有一些变通办法也不太像贫民区。一种方法是创建一个抽象控制器,从中扩展rest模块中的所有控制器。
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文件中的原因是,由于Zend Framework首先抛出了异常,因此从未调用init((函数中的set_exception_handler((。将其放入引导程序文件中将与此相反。
终于自己解决了问题:(
来自Zend文档:
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);
在CCD_ 5之前使其工作。