通常,應用會在運行過程中遇到一些錯誤,Zend Framework提供了對錯誤的拋出和捕捉機制,這樣可以對異常進行靈活的處理。
如果要在頁面上顯示錯誤消息,需要在配置文件中打開錯誤配置,如下:
resources.frontController.params.displayExceptions = 1phpSettings.display_startup_errors = 1phpSettings.display_errors = 1
/zf_demo1/application/controllers/ErrorController.php
<?phpclass ErrorController extends Zend_Controller_Action{ public function errorAction() { $errors = $this->_getParam('error_handler'); if (!$errors || !$errors instanceof ArrayObject) { $this->view->message = 'You have reached the error page'; return; } switch ($errors->type) { case Zend_Controller_Plugin_ErrorHandler::EXCEPTION_NO_ROUTE: 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); $priority = Zend_Log::NOTICE; $this->view->message = 'Page not found'; break; default: // application error $this->getResponse()->setHttpResponseCode(500); $priority = Zend_Log::CRIT; $this->view->message = 'Application error'; break; } // Log exception, if logger available if ($log = $this->getLog()) { $log->log($this->view->message, $priority, $errors->exception); $log->log('Request Parameters', $priority, $errors->request->getParams()); } // conditionally display exceptions if ($this->getInvokeArg('displayExceptions') == true) { $this->view->exception = $errors->exception; } $this->view->request = $errors->request; } public function getLog() { $bootstrap = $this->getInvokeArg('bootstrap'); if (!$bootstrap->hasResource('Log')) { return false; } $log = $bootstrap->getResource('Log'); return $log; }}
<!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 Default Application</title></head><body> <h1>An error occurred</h1> <h2><?php echo $this->message ?></h2> <?php if (isset($this->exception)): ?> <h3>Exception information:</h3> <p> <b>Message:</b> <?php echo $this->exception->getMessage() ?> </p> <h3>Stack trace:</h3> <pre><?php echo $this->exception->getTraceAsString() ?> </pre> <h3>Request Parameters:</h3> <pre><?php echo $this->escape(var_export($this->request->getParams(), true)) ?> </pre> <?php endif ?></body></html>
ErrorController不是必須的,但是通過ErrorController可以打印異常堆棧,對查找異常位置,定位異常,找到解決方法。對于異常的處理可以在這里進行統一的處理。
Controller中的trycatch進行拋出。
trycatch的基本用法如下:
try { Zend_Loader::loadClass('nonexistantclass');} catch (Zend_Exception $e) { echo "Caught exception: " . get_class($e) . ""; echo "Message: " . $e->getMessage() . ""; // 處理錯誤的代碼}
Zend_Framework定義了用到的常見的異常,默認的異常是 Zend_Exception。如果有必要,你可以定義自己的異常類。Zend_Framework處理異常的機制這里不做解釋,可以自行分析源代碼。
上一篇 php $_get[]用法