When there is an error in a Symfony 2 application an exception is generated. The framework produces a very detailed report when in the development environment. However, when you put the application in the production server, you will need to display a user friendly page.

Creating a custom page is actually simple. All you need to do is define a controller/action pair that will generate the response. You can either use an existing controller or create one specifically to handle errors. In our projects we are creating an “ExceptionController” and exceptonAction inside our bundle. This way we mimic what Symfony does in the FrameworkBundle.

Since you would be doing this for production only, a lean controller that just renders the template would be sufficient. A basic controller would look like:


namespace Application\ServerGrove\SGBundle\Controller;

use Symfony\Component\HttpKernel\Exception\FlattenException;
use Symfony\Component\HttpKernel\Log\DebugLoggerInterface;

class ExceptionController extends \Symfony\Bundle\FrameworkBundle\Controller\Controller
     * Converts an Exception to a Response.
     * @param FlattenException     $exception A FlattenException instance
     * @param DebugLoggerInterface $logger    A DebugLoggerInterface instance
     * @param string               $format    The format to use for rendering (html, xml, ...)
     * @param Boolean              $embedded  Whether the rendered Response will be embedded or not
     * @throws \InvalidArgumentException When the exception template does not exist
    public function exceptionAction(FlattenException $exception, DebugLoggerInterface $logger = null, $format = 'html', $embedded = false)
        return $this->render('SGBundle:Exception:error',
                    'exception' => $exception,


The Resources/views/Exception/error.php template would look like:

<?php $view->extend('SGBundle::layout_error') ?>
<h1>The server returned a "<?php echo $exception->getStatusCode() ?> <?php echo $exception->getStatusText() ?>" error.</h1>

   Ouch, something broke. Please send us an email and let us know
    what you were doing when this error occurred. We will fix it as soon
    as possible. Sorry for any inconvenience caused.

Notice that we are using a custom layout called layout_error. This is the new Symfony 2 template component that allows you to render different layouts down to the error page.

For the final step you need to tell Symfony to use your controller to handle exceptions. Set the following in config_prod.yml:

    exception_listener.controller: "SGBundle:Exception:exception"

That’s it! Enjoy your custom error pages in Symfony 2.

We want to thank Kris Wallsmith for his help on this topic.