遇到致命错误时,重定向到onBootstrap中的错误页面

时间:2014-05-18 01:59:49

标签: php zend-framework2

我正在尝试在遇到致命错误时将用户重定向到错误页面。我想在onBootstrap方法中重定向,就像这样。

<?php
use Zend\Mvc\MvcEvent;

class Module
{
    public function onBootstrap(MvcEvent $e)
    {
        $eventManager   = $e->getApplication()->getEventManager();
        $serviceManager = $e->getApplication()->getServiceManager();

        register_shutdown_function(function (MvcEvent $event)
        {
            $response = $event->getResponse();
            $response->setHeaders(
                $response->getHeaders()->addHeaderLine('Location', "/error-page")
            );
            $response->setStatusCode(302);
            $response->sendHeaders();
            return $response;
        });     
    }
}
?>

但是,我收到一条错误说:

    Catchable fatal error: Argument 1 passed to 
MyException\Module::MyException\{closure}() must be an instance of 
Zend\Mvc\MvcEvent, none given in MyException\Module.php on line 11.

还有其他方法可以重定向用户吗?

我也尝试了这一点,但我收到标题已发送错误。

register_shutdown_function(function ()
        {
            ob_clean();
            ob_flush();
            ob_start();
            header ('Location: /');
            ob_end();
        });

关于如何解决此问题的任何想法?

谢谢,

1 个答案:

答案 0 :(得分:1)

试试这个:

public function onBootstrap(MvcEvent $e){
    $e->setError('my-custom-error');
    $event->getTarget()->getEventManager()->trigger('dispatch.error', $e);
}

    public function onDispatchError(MvcEvent $event)
    {
        // Do nothing if the result is a response object
        $result = $event->getResult();
        if ($result instanceof Response) {
            return;
        }

        // Common view variables
        $viewVariables = array(
            'error' => $event->getParam('error'),
        );

        $error = $event->getError();
        switch ($error) {
            case 'my-custom-error':
                $viewVariables['key'] = $value;                
                break;
            default:
                /*
                 * do nothing if there is no error in the event or the error
                 * does not match one of our predefined errors (we don't want
                 * our 403.phtml to handle other types of errors)
                 */
                return;
        }

        $model = new ViewModel($viewVariables);
        $model->setTemplate('my-error-page');
        $event->getViewModel()->addChild($model);

        $response = $event->getResponse();
        if (!$response) {
            $response = new HttpResponse();
            $event->setResponse($response);
        }
        $response->setStatusCode(403);
    }