Custom error pages in Symfony

Even if we make our best efforts to keep everything perfect, 500 errors do happen. So in order to handle all my this-code-should-not-be-reached tests gracefully, I have a custom made error page.

The setup is quite simple actually : inside my views folder, I create a special folder named Error , and inside it I place this file : raise_custom_page_error.html.twig . I usually make this template a standalone file, meaning that Symfony can load it without needing any other main template. The main error displaying is done by the following code :

<div class="middle-box text-center">
    <h1>#42</h1>
    <h3 class="font-bold">Error</h3>

    <div class="error-desc">
        The server has encountered an error. 
        <br>
        Code : {{ error_number }}
        <br><br>
        <a href="{{ path("cookiejar_go_to_jail_do_not_pass_go") }}" class="btn btn-w-m btn-danger">Home</a>
    </div>
</div>

Now, whenever I have some test in the Controller which should never test false, I call my error template like this :

<?php

if ($cookieJar->getCookies() === null)
{
    // This should not happen
    // Do some error logging also ...
    
    // Send user to custom_error_page
    return $this->render(
        'CookiejarBundle:Error:raise_custom_page_error.html.twig',
        array (
            'error_number'		=>	'3141592',
        )
    );
}

That’s all it takes. The result is something like this :

 

I have also discovered this technique to be useful when in development mode also. Sometimes when I am on big projects, it happens that I accidentally create incoherent data when testing. And each time this #42 pops out, I can copy the error code, do a quick search inside my project and find the culprit.

I hope this is useful 😉

One thought to “Custom error pages in Symfony”

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.