How to set a custom ErrorRenderer in symfony 5?

Viewed 378

Problem: I tried to register a CustomErrorRenderer on Symfony 5 to render my CustomException, but all the time the TwigErrorRenderer is called. I thought probably self-defined renderers might be preferred?

CustomErrorRenderer.php:

namespace App\ErrorRenderer;
use Symfony\Component\ErrorHandler\Exception\FlattenException;
use Symfony\Component\ErrorHandler\ErrorRenderer\ErrorRendererInterface;


class CustomErrorRenderer implements ErrorRendererInterface
{
    public function render(\Throwable $exception): FlattenException
    {
        dd('CustomErrorRenderer.render() called');
        // TODO check if CustomException, else refer to preset renderer...

    }
}

services.yaml:

services:
    App\ErrorRenderer\CustomErrorRenderer:
        tags: ['error_renderer.renderer']
        # also tried: ['error_renderer.renderer', 'error_renderer.html','error_handler.error_renderer' , 'error_handler.error_renderer.html']

What is wrong with that?

Background: I have a web application and want to handle exceptions that are related to my internal business logic separately. E.g., a user wants to book a resource but it is currently not available. While current errors/exceptions are handled by the TwigErrorRenderer (or default HtmlErrorRenderer), I would like to add my own Renderer (ideally just extending the TwigErrorRenderer, so that I can use some specific, self-defined twig templates). By that, I aim to have a better UI, e.g., my custom exceptions being rendered while still the menu of the web application is shown. As my exceptions are not related to how the data is accessed (e.g. http), I do not want to use HttpExceptions and their status code.

1 Answers

This was not particularly easy to figure out.

I made a copy of vendor/symfony/twig-bridge/ErrorRenderer/TwigErrorRenderer.php into my app src\CustomerErrorRenderer.php.

Then override the error_renderer in services.yaml:

services:
    error_renderer:
        class: App\CustomErrorRenderer
        arguments: ['@twig', '@error_handler.error_renderer.html','%kernel.debug%']

Of course, that's not exactly how they call in their code when I tried to test using /_error/404 for instance.

They actually use arguments more like:

  error_renderer:
    class: App\Twig\CustomErrorRenderer
    arguments:
      - '@twig'
      - '@error_handler.error_renderer.html'
      - !service
        factory: [ 'Symfony\Component\ErrorHandler\ErrorRenderer\HtmlErrorRenderer', 'getAndCleanOutputBuffer' ]
        arguments: ['@request_stack']
Related