0

我正在调用一个我知道可能导致错误的方法,我试图通过将代码包装在 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

任何人都可以解释为什么会发生这种情况以及如何让它工作吗?

谢谢

4

4 回答 4

3

利用

if (class_exists('Application_Model_NonExistent')) {
    $test = new Application_Model_NonExistent;
} else {
    echo 'class not found.';
}

就像@prodigitalson 说你无法捕捉到那个致命错误。

于 2013-02-22T18:16:12.527 回答
2

错误和异常不是一回事。抛出异常并被捕获,其中错误通常不可恢复并由http://www.php.net/manual/en/function.trigger-error.php触发

如果由于错误需要进行一些清理,可以使用http://www.php.net/manual/en/function.set-error-handler.php

于 2013-02-22T18:12:54.753 回答
0

那不是例外,那是一个FATAL错误,这意味着您无法像那样捕获它。根据定义, aFATAL不应该是可恢复的。

于 2013-02-22T18:12:17.907 回答
0

异常和错误是不同的东西。您正在使用一个 Exception 类,并且 $e 是它的对象。

你想处理错误,检查 php-zend 框架中的错误处理。但是在这里,这是一个致命的错误,你必须纠正它,不能处理。

于 2013-02-22T18:13:12.803 回答