Handling exceptions in a Front Controller plugin

If you have a Zend Framework Front Controller plugin which throws an exception, then the action is still executed and then the error action is then called, so that the displayed output shows two actions rendered, with two layouts also rendered. This is almost certainly not what you want or what you expected.

This is how to handle errors in a Front Controller plugin:

  1. Prefer preDispatch() over dispatchLoopStartup() as it is called from within the dispatch loop
  2. Catch the exception and the modify the request so that the error controller’s error action is dispatched.
  3. Create an error handler object so that the error action works as expected.

This is the code:


class Application_Plugin_Foo extends Zend_Controller_Plugin_Abstract
    public function preDispatch(Zend_Controller_Request_Abstract $request)
        try {

            // do something that throws an exception

        } catch (Exception $e) {
            // Repoint the request to the default error handler

            // Set up the error handler
            $error = new Zend_Controller_Plugin_ErrorHandler();
            $error->type = Zend_Controller_Plugin_ErrorHandler::EXCEPTION_OTHER;
            $error->request = clone($request);
            $error->exception = $e;
            $request->setParam('error_handler', $error);


That’s it.

From akrabat.com


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s