Zend Framework 2:为错误404设置原因短语

I want my controller to return a 404 response when a model is not found and I want to specify a custom message, not the default "The requested controller was unable to dispatch the request."

I have tried specifying the reason in the ViewModel, setting the reasonPhrase from the response object... nothing seems to work. I am currently investigating how I can prevent the default behaviour, but if someone know before I do, that would just be great. (Perhaps there's a better way than the one I would find anyhow, too.)

Here is what I have, which does not work :

 $userModel = $this->getUserModel();
 if (empty($userModel)) {
     $this->response->setStatusCode(404);
     $this->response->setReasonPhrase('error-user-not-found');
     return new ViewModel(array(
         'content' => 'User not found',
     ));
 }

Thanks.

Looks like you are confusing the reasponphrase and the reason variable passed on to the view. The reasonphrase is part of the http status code, like "Not Found" for 404. You probably don't want to change that.

Like @dphn is saying, I would recommend throwing your own Exception and attach a listener to the MvcEvent::EVENT_DISPATCH_ERROR which decides what to respond.

To get you started:

Controller

public function someAction()
{
    throw new \Application\Exception\MyUserNotFoundException('This user does not exist');
}

Module

public function onBootstrap(MvcEvent $e)
{
    $events = $e->getApplication()->getEventManager();

    $events->attach(
        MvcEvent::EVENT_DISPATCH_ERROR,
        function(MvcEvent $e) {
            $exception = $e->getParam('exception');
            if (! $exception instanceof \Application\Exception\MyUserNotFoundException) {
                return;
            }

            $model = new ViewModel(array(
                'message' => $exception->getMessage(),
                'reason' => 'error-user-not-found',
                'exception' => $exception,
            ));
            $model->setTemplate('error/application_error');
            $e->getViewModel()->addChild($model);

            $response = $e->getResponse();
            $response->setStatusCode(404);

            $e->stopPropagation();

            return $model;
        },
        100
    );
}

error/application_error.phtml

<h1><?php echo 'A ' . $this->exception->getStatusCode() . ' error occurred ?></h1>
<h2><?php echo $this->message ?></h2>  
<?php
switch ($this->reason) {
    case 'error-user-not-found':
      $reasonMessage = 'User not found';
      break;
}
echo $reasonMessage;

module.config.php

'view_manager' => array(
    'error/application_error' => __DIR__ . '/../view/error/application_error.phtml',
),