php - Symfony2 : Redirect user to index page when page not found or 404 errors thrown -
i want redirect user particular page when page not found error comes in symfony2.
for customization of error page message created
app\resources\twigbundle\views\exception\error404.html.twing
but want redirect user particular page. how can that?
thanks
you want create event listener listens kernel.exception
event kernel dispatches when encounters exception.
then, check inside listener if exception instance of notfoundhttpexception
, , if is, redirect page of choice.
here's exemple:
<?php // src/acme/demobundle/eventlistener/acmeexceptionlistener.php namespace acme\demobundle\eventlistener; use symfony\component\httpkernel\event\getresponseforexceptionevent; use symfony\component\httpfoundation\redirectresponse; use symfony\component\httpkernel\exception\notfoundhttpexception; class acmeexceptionlistener { public function onkernelexception(getresponseforexceptionevent $event) { // exception object received event $exception = $event->getexception(); if ($event->getexception() instanceof notfoundhttpexception) { $response = new redirectresponse($url); $event->setresponse($response); } } }
obviously, you'll need register event listener. service, need register usual.
# app/config/config.yml services: kernel.listener.your_listener_name: class: acme\demobundle\eventlistener\acmeexceptionlistener tags: - { name: kernel.event_listener, event: kernel.exception, method: onkernelexception }
Comments
Post a Comment