我有一個模塊Api,我試圖實現一個RESTful API。問題是,當我在該模塊中引發異常時,我想要引發異常並且不由缺省模塊中的錯誤控制器處理。如何爲特定模塊禁用錯誤控制器
是否可以爲Zend Framework中的特定模塊禁用錯誤控制器?
我有一個模塊Api,我試圖實現一個RESTful API。問題是,當我在該模塊中引發異常時,我想要引發異常並且不由缺省模塊中的錯誤控制器處理。如何爲特定模塊禁用錯誤控制器
是否可以爲Zend Framework中的特定模塊禁用錯誤控制器?
使用以下方法可以禁用特定模塊的錯誤處理程序。在這個例子中,我將調用你的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
模塊,我們將註冊該插件。這是在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中註冊該插件。
希望有所幫助。
謝謝,這幫了我很多。我想只在拋出異常時顯示錯誤的XML響應。 – 2012-02-04 16:17:22
我認爲在那種情況下,你想使用第二種方法。否則,異常將一路回到前端控制器並關閉錯誤處理,我認爲您最終會得到一個異常返回到PHP,在生產環境中,您通常最終會遇到500服務器錯誤。如果爲模塊設置了錯誤處理程序,則可以讓控制器記錄異常,以防異常用戶輸入引起,並且錯誤視圖腳本可以無條件地顯示錶示錯誤狀態的XML響應。 – drew010 2012-02-04 19:50:50
再想一想,您仍然可以使用默認模塊中的默認錯誤處理程序,只需將當前模塊分配給ErrorController中的視圖,並在模塊休息時顯示XML,或者您可能出現錯誤控制器呈現error.xml.phtml或類似的東西。 – drew010 2012-02-04 19:51:56