Module-based error handling

by Naneau

Just a short post today. #zftalk is a good source of inspiration for me. Today Dan asked if it was possible to make the error handler use an ErrorController based on the module the error occurred in. There are some good reasons for why you would want this. For instance, your module may raise errors that are specific to it’s environment, and therefore can be handled better in it’s own error handling controller. On the other hand, it will add complexity to your application, and, in the case of an error, complexity is the last thing you want.

At any rate, the most basic approach to make a module have it’s own ErrorController would be like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
/**
 * init hook, gets executed before any action is dispatched
 */

public function init() {
   
    $front = Zend_Controller_Front::getInstance();
    $errorHandler = $front->getPlugin('Zend_Controller_Plugin_ErrorHandler');
    //the error handler plugin
    $moduleName = $this->getRequest()->getModuleName();
    //module name
    $errorHandler->setErrorHandlerModule($moduleName);
    //set the current module as the error handler module
}

At controller initialization, you retrieve the error handler from the front controller and tell it to use a specific module (the current module) for it’s error controller. This is a foolproof way of doing it. You may also automate this by subclassing the error handler plugin, or write a small plugin to do this for all controllers. But hey, this is fool-proof! ;)