我有一个模块Api,我正在尝试实现RESTful API。问题是当我在该模块中抛出异常时,我希望抛出异常而不是由默认模块中的错误控制器处理。
是否可以在Zend Framework中仅为特定模块禁用错误控制器?
答案 0 :(得分:4)
使用以下方法可以禁用特定模块的错误处理程序。在此示例中,我将调用您的RESTful模块rest
。
首先,在您的应用程序中创建一个新插件。例如,这将是Application_Plugin_RestErrorHandler
。将以下代码添加到application/plugins/RestErrorHandler.php
class Application_Plugin_RestErrorHandler extends Zend_Controller_Plugin_Abstract
{
public function preDispatch(Zend_Controller_Request_Abstract $request)
{
$module = $request->getModuleName();
// don't run this plugin unless we are in the rest module
if ($module != 'rest') return ;
// disable the error handler, this has to be done prior to dispatch()
Zend_Controller_Front::getInstance()->setParam('noErrorHandler', true);
}
}
接下来,在rest
模块的模块Bootstrap中,我们将注册该插件。这是modules/rest/Bootstrap.php
。由于无论当前模块如何都会执行所有模块引导,因此它可以进入主引导程序,但我喜欢在该模块的引导程序中注册与特定模块相关的插件。
protected function _initPlugins()
{
$bootstrap = $this->getApplication();
$bootstrap->bootstrap('frontcontroller');
$front = $bootstrap->getResource('frontcontroller');
// register the plugin
$front->registerPlugin(new Application_Plugin_RestErrorHandler());
}
另一种可能性是保留错误处理程序,但使用模块特定的错误处理程序。这样,rest
模块的错误处理程序可能会有不同的行为,并输出REST友好错误。
为此,请将ErrorController.php
复制到modules/rest/controllers/ErrorController.php
,然后将该课程重命名为Rest_ErrorController
。接下来,将错误控制器的视图脚本复制到modules/rest/views/scripts/error/error.phtml
。
根据自己的喜好自定义error.phtml,以便错误消息使用与其余模块相同的JSON / XML格式。
然后,我们将对上面的插件稍作调整。我们要做的是告诉Zend_Controller_Front使用rest
模块中的ErrorController :: errorAction而不是默认模块。如果需要,您甚至可以使用与ErrorController不同的控制器。将插件更改为如下所示:
class Application_Plugin_RestErrorHandler extends Zend_Controller_Plugin_Abstract
{
public function preDispatch(Zend_Controller_Request_Abstract $request)
{
$module = $request->getModuleName();
if ($module != 'rest') return ;
$errorHandler = Zend_Controller_Front::getInstance()
->getPlugin('Zend_Controller_Plugin_ErrorHandler');
// change the error handler being used from the one in the default module, to the one in the rest module
$errorHandler->setErrorHandlerModule($module);
}
}
使用上述方法,您仍然需要在Bootstrap中注册插件。
希望有所帮助。