Symfony 5 custom 404 page

I’m trying to create a custom 404 page for a Symfony 5 project that must:

  1. Output a simple JSON-encoded string, like “Not found”.
    • Said string must be read from a translation resource.
  2. Have an additional Content-Type: application/json header.

There is a section in the Symfony docs, that attempts to explain how this can be achieved, but the information seems incomplete/incorrect, apparently being written for the 4.X version, even pointing to non-existent source files on GitHub.

I have managed to create an error controller, but it swallows all errors:

# config/packages/framework.yaml
    error_controller: AppControllerErrorController::errorHandler
// src/Controller/ErrorController.php
class ErrorController extends AbstractController
    public function errorHandler(TranslatorInterface $translator) : JsonResponse
        return new JsonResponse($translator->trans('not_found'));

The problem is that this results in any error (including internal ones) returning a 404 page.

How can I make this controller/method handle only 404 errors and leave everything else to be handled as before by the framework itself?

Source: Symfony Questions

Was this helpful?

0 / 0

Leave a Reply 0

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