intro
This article introduces an error handling described in Programmer’s Reference Guide of Zend Framework(see the section 7.10.5.2).You can download the source code of this article from here.
1.Create Controllers
Create the file
application/constorllers/ErrorController.php
with the following content.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 |
<?php class ErrorController extends Zend_Controller_Action { public function errorAction() { $errors = $this->_getParam('error_handler'); switch ($errors->type) { case Zend_Controller_Plugin_ErrorHandler::EXCEPTION_NO_CONTROLLER: case Zend_Controller_Plugin_ErrorHandler::EXCEPTION_NO_ACTION: // 404 error -- controller or action not found $this->getResponse()->setRawHeader('HTTP/1.1 404 Not Found'); $this->view->title = '404 Not Found'; $this->view->message = 'The page you requested was not found.'; break; default: // application error // log error //require_once 'Zend/Log.php'; //require_once 'Zend/Log/Writer/Stream.php'; //$stream = new Zend_Log_Writer_Stream('/path/to/logfile'); //$logger = new Zend_Log($stream); //$exception = $errors->exception; //$logger->err($exception->getMessage() // . "\n" . $exception->getTraceAsString()); $this->view->title = 'Error'; $this->view->message = 'An unexpected error occurred with your request. ' . ' Please try again later.'; break; } // Clear previous content $this->getResponse()->clearBody(); } } |
Create the file application/constorllers/IndexController.php
with the following content.
1 2 3 4 5 6 7 8 9 10 11 |
<?php require_once 'Zend/Controller/Action.php'; require_once 'Zend/Exception.php'; class IndexController extends Zend_Controller_Action { public function indexAction() { throw new Zend_Exception('some error occured...'); } } |
2.Create View
Create the file
application/views/scripts/error/error.phtml
with the following content.
1 2 3 4 5 6 7 8 9 10 11 12 |
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title><?=$this->translate($this->title)?></title> </head> <body> <h1><?=$this->translate($this->title)?></h1> <p><?=$this->translate($this->message)?></p> </body> </html> |
3.Check
Let’s access your web server(ex.http://localhost/), and check the error screen. If you’ve modified your error controller to log exception, please check the log file too.
History
Date | Content |
---|---|
2008/4/3 | Published |
2008/4/15 | 404 error message is fixed |
The bug to which the 404 error message was not correctly displayed was corrected.