Reputation: 8511
I am trying to redirect Symfony to another route /404
if there is a 404 error. In the ExceptionController.php
file, I am looking for the error code 404. When error 404 is present, redirect to my-domain.com/404
. I want to redirect my users to another 404 page is because my custom 404 page is from another bundle.
Below is the code I have written. When I go to a non-existing website, I am presented with a 500 server error page instead of my expected redirected 404 page. Am I missing something?
if ($code == '404') {
return $this->redirect("/404");
}
Upvotes: 0
Views: 8072
Reputation: 7808
I've had a look, and as far as I know it's not possible to have error pages within a
bundle. It has to be a site wide one found in app/Resources/views/Exception/error404.html.twig
However you can return a custom Response by leveraging the HttpFoundation component
<?php
namespace Acme\WhateverBundle\Controller;
//...
use Symfony\Component\HttpFoundation\Response;
class MyController extends Controller
{
//...
public function takeAction()
{
//..
if ($notFound) {
$twig = $this->container->get('templating');
$content = $twig->render('AcmeAnotherBundle:Exception:error404.html.twig');
return new Response($content, 404, array('Content-Type', 'text/html'));
}
// ...
return $this->render('AcmeWhateverBundle:Default:index.html.twig');
}
}
Upvotes: 2
Reputation: 2374
You might try using Symfony's createNotFoundException() method:
http://symfony.com/doc/2.0/book/controller.html#managing-errors-and-404-pages
Instead of redirecting to a 404 page, try this in your controller:
throw $this->createNotFoundException('This page does not exist.');
Upvotes: 1