我正在调用一个我知道可能会导致错误的方法,我正试图通过将代码包装在try/catch语句中来处理错误。。。
class TestController extends Zend_Controller_Action
{
public function init()
{
// Anything here happens BEFORE the View has rendered
}
public function indexAction()
{
// Anything `echo`ed here is added to the end of the View
$model = new Application_Model_Testing('Mark', 31);
$this->view->sentence = $model->test();
$this->loadDataWhichCouldCauseError();
$this->loadView($model); // this method 'forwards' the Action onto another Controller
}
private function loadDataWhichCouldCauseError()
{
try {
$test = new Application_Model_NonExistent();
} catch (Exception $e) {
echo 'Handle the error';
}
}
private function loadView($model)
{
// Let's pretend we have loads of Models that require different Views
switch (get_class($model)) {
case 'Application_Model_Testing':
// Controller's have a `_forward` method to pass the Action onto another Controller
// The following line forwards to an `indexAction` within the `BlahController`
// It also passes some data onto the `BlahController`
$this->_forward('index', 'blah', null, array('data' => 'some data'));
break;
}
}
}
但我遇到的问题是错误没有得到处理。查看应用程序时,我收到以下错误。。。
( ! ) Fatal error: Class 'Application_Model_NonExistent' not found in /Library/WebServer/Documents/ZendTest/application/controllers/TestController.php on line 23
有人能解释为什么会发生这种情况,以及我如何才能让它发挥作用吗?
感谢
使用
if (class_exists('Application_Model_NonExistent')) {
$test = new Application_Model_NonExistent;
} else {
echo 'class not found.';
}
就像@magnittalson说的那样,你抓不到那个致命的错误。
错误和异常不是一回事。异常被抛出并被捕获,其中错误通常是不可恢复的,并用http://www.php.net/manual/en/function.trigger-error.php
- PHP:异常与错误
- 我能提醒一下吗
如果由于错误而需要进行一些清理,可以使用http://www.php.net/manual/en/function.set-error-handler.php
这不是一个例外,这是一个FATAL
错误,意味着你不能像那样捕捉它。根据定义,FATAL
不应是可恢复的。
异常和错误是不同的。有一个Exception类,您正在使用它,$e是它的对象。
如果要处理错误,请检查php-zend框架中的错误处理。但在这里,这是一个致命的错误,你必须改正,不能处理。