Php Zend Framework 2:设置错误404的原因短语
我希望我的控制器在找不到模型时返回404响应,并且我希望指定自定义消息,而不是默认的“Php Zend Framework 2:设置错误404的原因短语,php,http-headers,zend-framework2,http-status-code-404,Php,Http Headers,Zend Framework2,Http Status Code 404,我希望我的控制器在找不到模型时返回404响应,并且我希望指定自定义消息,而不是默认的“请求的控制器无法发送请求。” 我已尝试在ViewModel中指定reason,从响应对象设置reasonPhrase。。。似乎什么都不管用。我目前正在研究如何防止默认行为,但如果有人在我之前知道,那就太好了。(也许还有比我无论如何都能找到的更好的方法。) 以下是我所拥有的,但不起作用: $userModel = $this->getUserModel(); if (empty($userModel))
请求的控制器无法发送请求。
”
我已尝试在ViewModel
中指定reason
,从响应对象设置reasonPhrase
。。。似乎什么都不管用。我目前正在研究如何防止默认行为,但如果有人在我之前知道,那就太好了。(也许还有比我无论如何都能找到的更好的方法。)
以下是我所拥有的,但不起作用:
$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',
));
}
谢谢。看起来您混淆了传递给视图的reasonphrase和reason变量。原因短语是http状态代码的一部分,如404的“未找到”。你可能不想改变这一点 正如@dphn所说,我建议抛出您自己的异常,并将侦听器附加到决定响应内容的
MvcEvent::EVENT\u DISPATCH\u ERROR
要开始,请执行以下操作:
控制器
模块
错误/应用程序错误.phtml
“请求的控制器无法发送请求。”由page not found事件处理程序返回,而不是由您的控制器返回。请参阅404模板。如果您使用应用程序模块,请参阅Application/view/error/404.phtml开关($this->reason){…}@dphn,是的,关键是我在控制器中设置了原因,它在渲染阶段之间被覆盖。@imel96,您能详细说明一下吗?注释本身无助于解决此处的问题。控制器由EventManager在EVENT_DISPATCH事件中调度,但前提是可以调度控制器。如果不能,则会触发一个事件\u DISPATCH\u错误,您的代码不会被执行,它将显示view/ERROR/404.phtml。Otoh,如果控制器被调度,我觉得你的代码很好。对不起,如果不回答,我想是路由问题吧?
public function someAction()
{
throw new \Application\Exception\MyUserNotFoundException('This user does not exist');
}
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
);
}
<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;
'view_manager' => array(
'error/application_error' => __DIR__ . '/../view/error/application_error.phtml',
),