Developing software in the Real World

Displaying errors in Expressive with Twig

If you're not using the Whoops error handler with Expressive and are using the Twig renderer, then you are given no information about the problem that occurred, even in debug mode.

To fix this, I changed error.html.twig to this:

The new part is the within the {% if error %} block. In debug mode, error is set to the exception that was thown and is blank otherwise, so you won't leak sensitive information (as long as you don't enable debug in production).

Inside the {% if error %} block, I render the error message and where it happened and then iterate down through any previous errors and displays their information too. Interestingly, there isn't a while loop in Twig which would be ideal to recursively iterate through the previous errors. To solve this, I used the construct which works nicely as long as I don't have more than 10,000 previous errors!

If you use the Zend-View or Plates rendering engines, I imagine similar code would work there too.

Thoughts? Leave a reply

Your email address will not be published. Required fields are marked *