2

In my Module.php I have attached a handler to catch exceptions. This works, but I'm not sure how I setup a response and view template.

My code below attempts to set the responce code to 409 and display the 409.phtml template. However it does not work, it just renders the original 500 error page.

public function onBootstrap(MvcEvent $e)
{
    $eventManager        = $e->getApplication()->getEventManager();
    $moduleRouteListener = new ModuleRouteListener();
    $moduleRouteListener->attach($eventManager);

    $eventManager->attach(\Zend\Mvc\MvcEvent::EVENT_DISPATCH_ERROR, array($this, 'handleError'));
}

public function handleError(MvcEvent $event)
{
    //get the exception
    $exception = $event->getParam('exception');
    if (is_a($exception, 'Doctrine\DBAL\Exception\ForeignKeyConstraintViolationException'))
    {
        $response = $event->getResponse();
        $response = $response ?: new Response();
        $model    = new ViewModel(array());
        $model->setTemplate('error\409');
        $event->getViewModel()->addChild($model);
        $response->setStatusCode(409);
        $event->setResponse($response);
        return $response;
    }
}
srayner
  • 1,799
  • 4
  • 23
  • 39
  • Try a higher priority. The default exception strategy `Zend\Mvc\View\Http\ExceptionStrategy` is [registered with the default priority of 1](https://github.com/zendframework/zend-mvc/blob/master/src/View/Http/ExceptionStrategy.php#L39). This would result in the it being executed before yours. Also, note that this class uses `$event->setResult($model);` rather than `$event->getViewModel()->addChild($model)`. – AlexP Jan 21 '16 at 19:13
  • The handler was catching the exception ok and response code was correctly set to 409. It's just it was then going on to display the 500 error page. I seem to have solved it with stopPropergation(). I will try to take a look at setResult($model) when I get a chance. Thanks for comment. – srayner Jan 22 '16 at 20:32

1 Answers1

0

This seems to work, but it would be interesting to know what others think.

public function handleError(MvcEvent $event)
{
    //get the exception
    $exception = $event->getParam('exception');
    if (is_a($exception, 'Doctrine\DBAL\Exception\ForeignKeyConstraintViolationException'))
    {
        $event->getResponse()->setStatusCode(409);
        $model    = new ViewModel(array());
        $model->setTemplate('error/409');
        $event->getViewModel()->clearChildren();
        $event->getViewModel()->addChild($model);
        $event->stopPropagation(true);
    }
}
akond
  • 15,865
  • 4
  • 35
  • 55
srayner
  • 1,799
  • 4
  • 23
  • 39