I may be going about this completely the wrong way, but I have a onKernelRequest event setup which picks up the current domain (multi site on a single application), queries cache/db and stores this in the service for use by other controllers/services. This works perfectly.
Now if the domain isn't found, I'd like to throw a 404 error. Usually I'd just do the following in a controller:
throw new NotFoundHttpException('Not found!');
But this results in an uncaught exception in production, so I'm assuming due to the priority of the event (31).
PHP Fatal error: Uncaught exception 'Symfony\Component\HttpKernel\Exception\NotFoundHttpException' with message 'Not found!'
My current code (with logic removed for clarity), note I use JMSDiExtraBundle to configure services.
/**
* @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...
}
}
My question is what would be the best way to display a 404 error when the domain doesn't exist?
Not sure if this is the most elegant solution, but I had the same problem and this worked for me:
When an exception is thrown and ExceptionListener catches it, it adds the exception to request attributes and replays the request. This causes the listeners to be notified again, and they will throw another exception for the same reason as the first time.
I solved (worked around?) this problem by checking if there's no exception set in the request in my listeners:
public function onKernelRequest(GetResponseEvent $event)
{
$request = $event->getRequest();
if ($request->attributes->has('exception')) {
return;
}
// ...
if ($somethingWasWrong) {
throw new NotFoundHttpException();
}
}
Now the condition for failure is not checked when the exception has already been thrown, and the exception will be handled appropriately.
EDIT: I looked into Symfony listeners and they check if the current request is the master request:
if (!$event->isMasterRequest()) {
return;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With