ErrorController.php
- <?php
- require_once 'Zend/Controller/Action.php';
- class ErrorController extends Zend_Controller_Action
- {
- public function init()
- {
- $this->view->baseUrl = $this->_request->getBaseUrl();
- }
- 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()->setHttpResponseCode(404);
- $this->view->message = 'Page not found 404';
- break;
- default:
- // application error
- $this->getResponse()->setHttpResponseCode(500);
- $this->view->message = 'Application error 500';
- break;
- }
- $this->view->env = $this->getInvokeArg('env');
- $this->view->exception = $errors->exception;
- $this->view->request = $errors->request;
- }
- }
error.phtml
- <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN";
- "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd>
- <html xmlns="http://www.w3.org/1999/xhtml">
- <head>
- <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
- <title>Zend Framework Quick Start</title>
- </head>
- <body>
- <h1>An error occurred</h1>
- <h2><?= $this->message ?></h2>
- <? if ('development' == $this->env): ?>
- <h3>Exception information:</h3>
- <p>
- <b>Message:</b> <?= $this->exception->getMessage() ?>
- </p>
- <h3>Stack trace:</h3>
- <pre>
- <?= $this->exception->getTraceAsString() ?>
- </pre>
- <h3>Request Parameters:</h3>
- <pre>
- <?= $this->request->getParams() ?>
- </pre>
- <? endif ?>
- </body>
- </html>
以上代码来自Zend的官方QuickStart。
注意:使用自定义错误处理,不能在启动页面index.php中设置:
- $frontController->throwExceptions(true);
因为,如果设置了直接抛出错误,则不会进入ErrorController。
本文介绍Zend框架中的ErrorController实现方式,包括如何针对不同类型的错误返回相应的HTTP状态码,并展示错误信息给用户。此外,还提供了在开发环境中显示详细错误信息的方法。
506

被折叠的 条评论
为什么被折叠?



