views:

60

answers:

2

Hi

I have a few modules, one is an API. I want to set a different ErrorHandler for this API module.

Because when the default ErrorHandler is fired it uses the default module with the default layout, which contains HTML. Which is something I do not want my API to be returning.

I have looked on here and at the Zend Docs and have not come up with anything that allows me to do this.

Thanks for any help.

A: 

Just off the top of my head, you could store a copy of the original request object in the registry from a controller plugin. In the preDispatch() of your controller you could then forward to another error controller based on the requested module.

// Plugin
public function routeStartup(Zend_Controller_Request_Abstract $request)
{
    $clonedRequest = clone $request;
    Zend_Registry::set('originalRequest', $clonedRequest);
}

// ErrorController
public function preDispatch()
{
    $request = Zend_Registry::get('originalRequest');
    $this->_forward('error', 'error', $request->getModuleName());
}
smack0007
+1  A: 

Here is the one I use:

<?php
class My_Controller_Plugin_Modular_ErrorController extends Zend_Controller_Plugin_Abstract
{
    public function routeShutdown (Zend_Controller_Request_Abstract $request)
    {
        $front = Zend_Controller_Front::getInstance();

        // Front controller has error handler plugin
        // if the request is an error request.
        // If the error handler plugin is not registered,
        // we will be unable which MCA to run, so do not continue.
        $errorHandlerClass = 'Zend_Controller_Plugin_ErrorHandler';
        if (!$front->hasPlugin($errorHandlerClass)) {

            return false;
        }

        // Determine new error controller module_ErrorController_ErrorAction
        $plugin = $front->getPlugin($errorHandlerClass);
        $errorController = $plugin->getErrorHandlerController();
        $errorAaction = $plugin->getErrorHandlerAction();
        $module = $request->getModuleName();

        // Create test request module_ErrorController_ErrorAction...
        $testRequest = new Zend_Controller_Request_Http();
        $testRequest->setModuleName($module)
            ->setControllerName($errorController)
            ->setActionName($errorAaction);

        // Set new error controller if available
        if ($front->getDispatcher()->isDispatchable($testRequest)) {
            $plugin->setErrorHandlerModule($module);
        } else {

            return false;
        }

        return true;
    }
}

(BTW, This issue already was discussed here, look carefully.)

takeshin