Previous Next

MVC Exceptions

Introduction

The MVC components in Zend Framework utilize a Front Controller, which means that all requests to a given site will go through a single entry point. As a result, all exceptions bubble up to the Front Controller eventually, allowing the developer to handle them in a single location.

However, exception messages and backtrace information often contain sensitive system information, such as SQL statements, file locations, and more. To help protect your site, by default Zend_Controller_Front catches all exceptions and registers them with the response object; in turn, by default, the response object does not display exception messages.

How can you handle exceptions?

Several mechanisms are built in to the MVC components already to allow you to handle exceptions.

  • By default, the error handler plugin is registered and active. This plugin was designed to handle:

    • Errors due to missing controllers or actions

    • Errors occurring within action controllers

    It operates as a postDispatch() plugin, and checks to see if a dispatcher, action controller, or other exception has occurred. If so, it forwards to an error handler controller.

    This handler will cover most exceptional situations, and handle missing controllers and actions gracefully.

  • Zend_Controller_Front::throwExceptions()

    By passing a boolean true value to this method, you can tell the front controller that instead of aggregating exceptions in the response object or using the error handler plugin, you'd rather handle them yourself. As an example:

    $front->throwExceptions(true);
    try {
        $front->dispatch();
    } catch (Exception $e) {
        // handle exceptions yourself
    }

    This method is probably the easiest way to add custom exception handling covering the full range of possible exceptions to your front controller application.

  • Zend_Controller_Response_Abstract::renderExceptions()

    By passing a boolean true value to this method, you tell the response object that it should render an exception message and backtrace when rendering itself. In this scenario, any exception raised by your application will be displayed. This is only recommended for non-production environments.

  • Zend_Controller_Front::returnResponse() and Zend_Controller_Response_Abstract::isException().

    By passing a boolean true to Zend_Controller_Front::returnResponse(), Zend_Controller_Front::dispatch() will not render the response, but instead return it. Once you have the response, you may then test to see if any exceptions were trapped using its isException() method, and retrieving the exceptions via the getException() method. As an example:

    $front->returnResponse(true);
    $response = $front->dispatch();
    if ($response->isException()) {
        $exceptions = $response->getException();
        // handle exceptions ...
    } else {
        $response->sendHeaders();
        $response->outputBody();
    }

    The primary advantage this method offers over Zend_Controller_Front::throwExceptions() is to allow you to conditionally render the response after handling the exception. This will catch any exception in the controller chain, unlike the error handler plugin.

MVC Exceptions You May Encounter

The various MVC components -- request, router, dispatcher, action controller, and response objects -- may each throw exceptions on occasion. Some exceptions may be conditionally overridden, and others are used to indicate the developer may need to consider their application structure.

As some examples:

  • Zend_Controller_Dispatcher::dispatch() will, by default, throw an exception if an invalid controller is requested. There are two recommended ways to deal with this.

    • Set the useDefaultControllerAlways parameter.

      In your front controller, or your dispatcher, add the following directive:

      $front->setParam('useDefaultControllerAlways', true);
      
      // or
      
      $dispatcher->setParam('useDefaultControllerAlways', true);

      When this flag is set, the dispatcher will use the default controller and action instead of throwing an exception. The disadvantage to this method is that any typos a user makes when accessing your site will still resolve and display your home page, which can wreak havoc with search engine optimization.

    • The exception thrown by dispatch() is a Zend_Controller_Dispatcher_Exception containing the text 'Invalid controller specified'. Use one of the methods outlined in the previous section to catch the exception, and then redirect to a generic error page or the home page.

  • Zend_Controller_Action::__call() will throw a Zend_Controller_Action_Exception if it cannot dispatch a non-existent action to a method. Most likely, you will want to use some default action in the controller in cases like this. Ways to achieve this include:

    • Subclass Zend_Controller_Action and override the __call() method. As an example:

      class My_Controller_Action extends Zend_Controller_Action
      {
          public function __call($method, $args)
          {
              if ('Action' == substr($method, -6)) {
                  $controller = $this->getRequest()->getControllerName();
                  $url = '/' . $controller . '/index';
                  return $this->_redirect($url);
              }
      
              throw new Exception('Invalid method');
          }
      }

      The example above intercepts any undefined action method called and redirects it to the default action in the controller.

    • Subclass Zend_Controller_Dispatcher and override the getAction() method to verify the action exists. As an example:

      class My_Controller_Dispatcher extends Zend_Controller_Dispatcher
      {
          public function getAction($request)
          {
              $action = $request->getActionName();
              if (empty($action)) {
                  $action = $this->getDefaultAction();
                  $request->setActionName($action);
                  $action = $this->formatActionName($action);
              } else {
                  $controller = $this->getController();
                  $action     = $this->formatActionName($action);
                  if (!method_exists($controller, $action)) {
                      $action = $this->getDefaultAction();
                      $request->setActionName($action);
                      $action = $this->formatActionName($action);
                  }
              }
      
              return $action;
          }
      }

      The above code checks to see that the requested action exists in the controller class; if not, it resets the action to the default action.

      This method is nice because you can transparently alter the action prior to final dispatch. However, it also means that typos in the URL may still dispatch correctly, which is not great for search engine optimization.

    • Use Zend_Controller_Action::preDispatch() or Zend_Controller_Plugin_Abstract::preDispatch() to identify invalid actions.

      By subclassing Zend_Controller_Action and modifying preDispatch(), you can modify all of your controllers to forward to another action or redirect prior to actually dispatching the action. The code for this will look similar to the code for overriding __call(), above.

      Alternatively, you can check this information in a global plugin. This has the advantage of being action controller independent; if your application consists of a variety of action controllers, and not all of them inherit from the same class, this method can add consistency in handling your various classes.

      As an example:

      class My_Controller_PreDispatchPlugin extends Zend_Controller_Plugin_Abstract
      {
          public function preDispatch(Zend_Controller_Request_Abstract $request)
          {
              $dispatcher =
                  Zend_Controller_Front::getInstance()->getDispatcher();
              $controller = $dispatcher->getController($request);
              if (!$controller) {
                  $controller =
                      $dispatcher->getDefaultControllerName($request);
              }
              $action     = $dispatcher->getAction($request);
      
              if (!method_exists($controller, $action)) {
                  $defaultAction = $dispatcher->getDefaultAction();
                  $controllerName = $request->getControllerName();
                  $response =
                      Zend_Controller_Front::getInstance()->getResponse();
                  $response->setRedirect('/' . $controllerName .
                                         '/' . $defaultAction);
                  $response->sendHeaders();
                  exit;
              }
          }
      }

      In this example, we check to see if the action requested is available in the controller. If not, we redirect to the default action in the controller, and exit script execution immediately.

Previous Next
Introduction to Zend Framework
Overview
Installation
Zend_Acl
Introduction
Refining Access Controls
Advanced Usage
Zend_Amf
Introduction
Zend_Amf_Server
Zend_Auth
Introduction
Database Table Authentication
Digest Authentication
HTTP Authentication Adapter
LDAP Authentication
Open ID Authentication
Zend_Cache
Introduction
The theory of caching
Zend_Cache frontends
Zend_Cache backends
Zend_Captcha
Introduction
Captcha Operation
Captcha Adapters
Zend_Config
Introduction
Theory of Operation
Zend_Config_Ini
Zend_Config_Xml
Zend_Config_Writer
Zend_Config_Writer
Zend_Console_Getopt
Introduction to Getopt
Declaring Getopt Rules
Fetching Options and Arguments
Configuring Zend_Console_Getopt
Zend_Controller
Zend_Controller Quick Start
Zend_Controller Basics
The Front Controller
The Request Object
The Standard Router
The Dispatcher
Action Controllers
Action Helpers
The Response Object
Plugins
Using a Conventional Modular Directory Structure
MVC Exceptions
Migrating from Previous Versions
Zend_Currency
Introduction to Zend_Currency
How to work with currencies
Migrating from Previous Versions
Zend_Date
Introduction
Theory of Operation
Basic Methods
Zend_Date API Overview
Creation of dates
Constants for General Date Functions
Working examples
Zend_Db
Zend_Db_Adapter
Zend_Db_Statement
Zend_Db_Profiler
Zend_Db_Select
Zend_Db_Table
Zend_Db_Table_Row
Zend_Db_Table_Rowset
Zend_Db_Table Relationships
Zend_Debug
Dumping Variables
Zend_Dojo
Introduction
Zend_Dojo_Data: dojo.data Envelopes
Dojo View Helpers
Dojo Form Elements and Decorators
Zend_Dom
Introduction
Zend_Dom_Query
Zend_Exception
Using Exceptions
Zend_Feed
Introduction
Importing Feeds
Retrieving Feeds from Web Pages
Consuming an RSS Feed
Consuming an Atom Feed
Consuming a Single Atom Entry
Modifying Feed and Entry structures
Custom Feed and Entry Classes
Zend_File
Zend_File_Transfer
Validators for Zend_File_Transfer
Filters for Zend_File_Transfer
Migrating from previous versions
Zend_Filter
Introduction
Standard Filter Classes
Filter Chains
Writing Filters
Zend_Filter_Input
Zend_Filter_Inflector
Zend_Form
Zend_Form
Zend_Form Quick Start
Creating Form Elements Using Zend_Form_Element
Creating Forms Using Zend_Form
Creating Custom Form Markup Using Zend_Form_Decorator
Standard Form Elements Shipped With Zend Framework
Standard Form Decorators Shipped With Zend Framework
Internationalization of Zend_Form
Advanced Zend_Form Usage
Zend_Gdata
Introduction to Gdata
Authenticating with AuthSub
Using the Book Search Data API
Authenticating with ClientLogin
Using Google Calendar
Using Google Documents List Data API
Using Google Health
Using Google Spreadsheets
Using Google Apps Provisioning
Using Google Base
Using Picasa Web Albums
Using the YouTube Data API
Catching Gdata Exceptions
Zend_Http
Zend_Http_Client - Introduction
Zend_Http_Client - Advanced Usage
Zend_Http_Client - Connection Adapters
Zend_Http_Cookie and Zend_Http_CookieJar
Zend_Http_Response
Zend_InfoCard
Introduction
Zend_Json
Introduction
Basic Usage
JSON Objects
XML to JSON conversion
Zend_Json_Server - JSON-RPC server
Zend_Layout
Introduction
Zend_Layout Quick Start
Zend_Layout Configuration Options
Zend_Layout Advanced Usage
Zend_Ldap
Introduction
Zend_Loader
Loading Files and Classes Dynamically
Loading Plugins
Zend_Locale
Introduction
Using Zend_Locale
Normalization and Localization
Working with Dates and Times
Supported locales
Migrating from previous versions
Zend_Log
Overview
Writers
Formatters
Filters
Zend_Mail
Introduction
Sending via SMTP
Sending Multiple Mails per SMTP Connection
Using Different Transports
HTML E-Mail
Attachments
Adding Recipients
Controlling the MIME Boundary
Additional Headers
Character Sets
Encoding
SMTP Authentication
Securing SMTP Transport
Reading Mail Messages
Zend_Measure
Introduction
Creation of Measurements
Outputting measurements
Manipulating Measurements
Types of measurements
Zend_Memory
Overview
Memory Manager
Memory Objects
Zend_Mime
Zend_Mime
Zend_Mime_Message
Zend_Mime_Part
Zend_OpenId
Introduction
Zend_OpenId_Consumer Basics
Zend_OpenId_Provider
Zend_Paginator
Introduction
Usage
Configuration
Advanced usage
Zend_Pdf
Introduction.
Creating and loading PDF documents.
Save changes to the PDF document.
Document pages.
Drawing
Document Info and Metadata.
Zend_Pdf module usage example
Zend_ProgressBar
Zend_ProgressBar
Zend_Registry
Using the Registry
Zend_Rest
Introduction
Zend_Rest_Client
Zend_Rest_Server
Zend_Search_Lucene
Overview
Building Indexes
Searching an Index
Query Language
Query Construction API
Character Set
Extensibility
Interoperating with Java Lucene
Advanced
Best Practices
Zend_Server
Introduction
Zend_Server_Reflection
Zend_Service
Introduction
Zend_Service_Akismet
Zend_Service_Amazon
Zend_Service_Audioscrobbler
Zend_Service_Delicious
Zend_Service_Flickr
Zend_Service_Nirvanix
Zend_Service_ReCaptcha
Zend_Service_Simpy
Introduction
Zend_Service_StrikeIron
Zend_Service_StrikeIron: Bundled Services
Zend_Service_StrikeIron: Advanced Uses
Zend_Service_Technorati
Zend_Service_Twitter
Zend_Service_Yahoo
Zend_Session
Introduction
Basic Usage
Advanced Usage
Global Session Management
Zend_Session_SaveHandler_DbTable
Zend_Soap
Zend_Soap_Server
Zend_Soap_Client
WSDL Accessor
AutoDiscovery
Zend_Test
Introduction
Zend_Test_PHPUnit
Zend_Text
Zend_Text_Figlet
Zend_Text_Table
Zend_TimeSync
Introduction
Working with Zend_TimeSync
Zend_Translate
Introduction
Adapters for Zend_Translate
Using Translation Adapters
Migrating from previous versions
Zend_Uri
Zend_Uri
Zend_Validate
Introduction
Standard Validation Classes
Validator Chains
Writing Validators
Zend_Version
Reading the Zend Framework Version
Zend_View
Introduction
Controller Scripts
View Scripts
View Helpers
Zend_View_Abstract
Zend_Wildfire
Zend_Wildfire
Zend_XmlRpc
Introduction
Zend_XmlRpc_Client
Zend_XmlRpc_Server
Zend Framework Requirements
PHP Version
PHP Extensions
Zend Framework Components
Zend Framework Dependencies
Zend Framework Coding Standard for PHP
Overview
PHP File Formatting
Naming Conventions
Coding Style
Zend Framework Performance Guide
Introduction
Class Loading
Internationalization (i18n) and Localization (l10n)
View Rendering
Copyright Information