Symfony Exception Display Your Custom Message

Roland Sands Design Custom Indian

Roland Sands Design Custom Indian

Let’s pretend that you don’t want to use the ugly default error pages that come with Symfony. So you create a template to override the default error template and it looks like this.

{% extends 'base.html.twig' %}

{% block body %}
    <h1>Resource not found</h1>
    <p>{{ status_text }}</p>
{% endblock %}

When you’re throwing this exception, you’re providing your own message, but {{ status_text }} is showing the default generic message.

throw new HttpException(404, 'Um, sorry but I have no idea what you are talking about.');

What you see rendered from {{ status_text }} is “Not found” rather than your snarky response.

In the error pages, you have access to the FlattenException object, so you need to fetch the exception’s message rather than status text. Do this instead.

{% extends 'base.html.twig' %}

{% block body %}
    <h1>Resource not found</h1>
    <p>{{ exception.message }}</p>
{% endblock %}
Share Button