【发布时间】:2019-08-17 10:36:08
【问题描述】:
我正在 Symfony 4 中构建一个自定义异常控制器来覆盖 Twig 包中包含的 ExceptionController 类。
我正在按照Symfony documentation for customizing error pages 执行此操作。
# config/packages/twig.yaml
twig:
exception_controller: App\Controller\Error::handleException
我使用自定义异常控制器的原因是因为我需要将一些附加变量传递给自定义BaseController 类提供的模板。
Symfony 文档提到以下关于使用自定义控制器的内容:
TwigBundle 使用的 ExceptionListener 类作为 kernel.exception 事件的侦听器创建将被分派到您的控制器的请求。此外,您的控制器将被传递两个参数:
exception A FlattenException instance created from the exception being handled. logger A DebugLoggerInterface instance which may be null in some circumstances.
我需要FlattenException 服务来确定错误代码,但从文档中不清楚这些参数是如何传递给自定义异常控制器的。
这是我的自定义异常控制器代码:
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));
}
}
【问题讨论】:
标签: php symfony exception symfony4 php-7.2