我可能会以完全错误的方式解决这个问题,但我有一个 onKernelRequest 事件设置,它获取当前域(单个应用程序上的多个站点),查询缓存/数据库并将其存储在服务中以供其他人使用 Controller /服务。这非常有效。
现在,如果找不到域,我想抛出 404 错误。通常我会在 Controller 中执行以下操作:
throw new NotFoundHttpException('Not found!');
但这会导致生产中出现未捕获的异常,所以我假设是由于事件的优先级 (31)。
PHP Fatal error: Uncaught exception 'Symfony\Component\HttpKernel\Exception\NotFoundHttpException' with message 'Not found!'
我当前的代码(为清楚起见删除了逻辑),注意我使用 JMSDiExtraBundle 来配置服务。
/**
* @Service
*/
class CurrentDomainListener
{
/**
* @Observe("kernel.request", priority=31)
*/
public function onKernelRequest(GetResponseEvent $event)
{
// find domain in cache/database...
if (!$domain) {
throw new NotFoundHttpException('Not found!');
}
// store domain in service...
}
}
我的问题是当域不存在时显示 404 错误的最佳方式是什么?
最佳答案
不确定这是否是最优雅的解决方案,但我遇到了同样的问题并且这对我有用:
当抛出异常并且 ExceptionListener
捕获它时,它将异常添加到请求属性并重播请求。这导致监听器再次收到通知,他们会出于与第一次相同的原因抛出另一个异常。
我通过检查我的监听器中的请求中是否没有设置异常来解决(解决?)这个问题:
public function onKernelRequest(GetResponseEvent $event)
{
$request = $event->getRequest();
if ($request->attributes->has('exception')) {
return;
}
// ...
if ($somethingWasWrong) {
throw new NotFoundHttpException();
}
}
现在当异常已经抛出时不检查失败条件,异常将被适本地处理。
编辑:我查看了 Symfony 监听器,他们检查当前请求是否是主请求:
if (!$event->isMasterRequest()) {
return;
}
关于php - Symfony2 在内核请求事件中抛出 404,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30617347/