通常,应用会在运行过程中遇到一些错误,Zend Framework提供了对错误的抛出和捕捉机制,这样可以对异常进行灵活的处理。
如果要在页面上显示错误消息,需要在配置文件中打开错误配置,如下:
resources.frontController.params.displayExceptions = 1
phpSettings.display_startup_errors = 1
phpSettings.display_errors = 1
Zend Framework的MVC中通过Zend_Controller_Front捕捉了异常,然后重定向到一个一般性的错误页面或者主页。Zend Framework提供的基本的抛出异常的处理如下:
/zf_demo1/application/controllers/ErrorController.php
<?php
class 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;
}
}
/zf_demo1/application/views/scripts/error/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 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) . "\n";
echo "Message: " . $e->getMessage() . "\n";
// 处理错误的代码
}
Zend_Framework定义了用到的常见的异常,默认的异常是 Zend_Exception。如果有必要,你可以定义自己的异常类。Zend_Framework处理异常的机制这里不做解释,可以自行分析源代码。