1

是否可以为 zend 框架提供自定义 500 错误页面?我的意思是 ErrorController 中的某些内容...如果您有 500 错误,请查看自定义视图渲染。

<?php
class ErrorController extends Zend_Controller_Action
{
    private $_notifier;
    private $_error;
    private $_environment;

    public function init()
    {
        parent::init();


        $this->_error = $this->_getParam('error_handler');
   }

    public function errorAction()
    {
        switch ($this->_error->type) {
            case Zend_Controller_Plugin_ErrorHandler::EXCEPTION_NO_CONTROLLER:
            case Zend_Controller_Plugin_ErrorHandler::EXCEPTION_NO_ACTION:
                $this->getResponse()->setHttpResponseCode(404);
                $this->view->message = 'Page not found';
                break;
            default:
                //Doesn't work
                $this->renderScript('error/500.phtml');
                $this->getResponse()->setHttpResponseCode(500);
            break;
        }
    }
}
4

1 回答 1

1

是的,这完全有可能,但这取决于您最终获得状态 500 的原因。

任何导致 Apache 网络服务器发出此状态的内容都无法被您的 ErrorController 以简单的方式拦截。

但是,如果您决定必须使用 HTTP 响应代码 500 退出某个操作,那么您可以自由地这样做。

一件重要的事情是:如果您抛出一个未被捕获的异常,Zend 框架将捕获它并重定向到错误控制器。此异常对象存储为“error_handler”参数中的属性“异常”。因此,在您的代码中,您应该能够询问您是否因为未捕获的异常而存在:

if (isset($this->_error->exception) && $this->_error->exception instanceof Exception) {
  // You got an exception
}

我个人认为我的控制器能够抛出 Controller_Exception ,它带有必须发出的 HTTP 状态代码。如果您需要对响应代码进行详细控制,则只有控制器应该决定响应端发生的情况。

About logging: Log errors where they happen. If something makes you throw an exception, the correct location for logging is right before the throw, I'd say. Of course you can always log in the error controller as well, to signal that the error that once might only be at warning level really did not get caught and really is an error, but this might not really tell you where stuff went wrong.

于 2012-11-13T20:35:00.770 回答