title: Custom Exception Controller in Symfony 4
body: <p>I am building a custom exception controller in Symfony 4 to overwrite the <code>ExceptionController</code> class included in the Twig bundle.</p>
  <p>I am doing this as per the <a href="https://symfony.com/doc/current/controller/error_pages.html" rel="nofollow noreferrer">Symfony documentation for customizing error pages</a>.</p>
  <pre><code># config/packages/twig.yaml
  twig:
      exception_controller: App\Controller\Error::handleException
  </code></pre>
  <p>The reason I am using a custom exception controller is because I need to pass some additional variable to the template that are given by a custom <code>BaseController</code> class.</p>
  <p>The Symfony docs mention the following about using a custom controller:</p>
  <blockquote>
  <p>The ExceptionListener class used by the TwigBundle as a listener of the kernel.exception event creates the request that will be dispatched to your controller. In addition, your controller will be passed two parameters:</p>
  <pre><code>exception
      A FlattenException instance created from the exception being handled.
  
  logger
      A DebugLoggerInterface instance which may be null in some circumstances. 
  </code></pre>
  </blockquote>
  <p>I need the <code>FlattenException</code> service to determine the error code but its not clear from the docs how these parameters are passed to the custom exception controller.</p>
  <p>Here is my custom exception controller code:</p>
  <pre><code>namespace App\Controller;
  
  use Symfony\Component\HttpFoundation\Response;
  use Symfony\Component\Debug\Exception\FlattenException;
  
  class Error extends BaseController {
  
      protected $debug, // this is passed as a parameter from services.yaml
                $code;  // 404, 500, etc.
  
      public function __construct(BaseController $Base, bool $debug) {
  
          $this-&gt;debug = $debug;
  
          $this-&gt;data = $Base-&gt;data;
  
          // I'm instantiating this class explicitly here, but have tried autowiring and other variations that all give an error.
          $exception = new FlattenException();
  
          $this-&gt;code = $exception-&gt;getStatusCode(); // empty
  
      }
  
      public function handleException(){
  
          $template = 'error' . $this-&gt;code . '.html.twig';
          return new Response($this-&gt;renderView($template, $this-&gt;data));
      }
  } 
  </code></pre>