I am building a custom exception controller in Symfony 4 to overwrite the ExceptionController
class included in the Twig bundle.
I am doing this as per the Symfony documentation for customizing error pages.
# config/packages/twig.yaml
twig:
exception_controller: App\Controller\Error::handleException
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 BaseController
class.
The Symfony docs mention the following about using a custom controller:
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:
exception A FlattenException instance created from the exception being handled. logger A DebugLoggerInterface instance which may be null in some circumstances.
I need the FlattenException
service to determine the error code but its not clear from the docs how these parameters are passed to the custom exception controller.
Here is my custom exception controller 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->debug = $debug;
$this->data = $Base->data;
// I'm instantiating this class explicitly here, but have tried autowiring and other variations that all give an error.
$exception = new FlattenException();
$this->code = $exception->getStatusCode(); // empty
}
public function handleException(){
$template = 'error' . $this->code . '.html.twig';
return new Response($this->renderView($template, $this->data));
}
}