我有一个定义的侦听器正在观察可能发生错误的onKernelException
。
class SpecificExceptionListener
{
public function onKernelException(GetResponseForExceptionEvent $event)
{
$exception = $event->getException();
if ($exception instanceof SpecificExceptionToBeProcessed) {
// ...
if ($somethingWentWrong) {
// here, redirect to the default/overriden Symfony error page
}
// ...
}
}
}
如果出现错误,如何重定向到标准/自定义错误页面?
答案 0 :(得分:1)
对于那些可能感兴趣的人,以下是如何做到的:
use Symfony\Bundle\TwigBundle\TwigEngine;
use Symfony\Component\HttpKernel\Event\GetResponseForExceptionEvent;
use Symfony\Component\HttpFoundation\Response;
// ...
class SpecificExceptionListener
{
protected $templating;
public function __construct(TwigEngine $templating)
{
$this->templating = $templating;
}
public function onKernelException(GetResponseForExceptionEvent $event)
{
$exception = $event->getException();
if ($exception instanceof SpecificExceptionToBeProcessed) {
// ...
if ($somethingWentWrong) {
// build response to display Symfony default error page
// replace by your own template if needed
$response = new Response();
$response->setContent(
$this->templating->render('TwigBundle:Exception:error.html.twig')
);
$event->setResponse($response);
return;
}
// ...
}
}
}