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!
Comments
I definitely like your blog Maurice ! It’s always very pratical use cases, concise, clear. I keep this one under the elbow
.
Thank you
fred
naneau, can you paste2.org a sample code for displaying error messages, line numbers, etc. using you code above?
Naneau, I am quickly becoming a fan of your site. Good Zend Framework tutorials are hard to find. As a noob to Zend Framework I would have to say that what I find most difficult is where to put code.
I think the value of your blog and example code would increase a lot if you always added a comment next to code as to where (as in what file) that code should be placed.
Having said all that, where should this code live? In each modules ErrorController? In Bootstrap or index?
Thank you for your contributions.