2013-12-18 31 views
4

我在我的控制器中抛出一些异常。Symfony 2.如何在Twig模板中捕获Exception参数?

例如:

throw new AccessDeniedHttpException('some_text'); 

我怎么能赶上它的'SOME_TEXT' 在我的枝条模板参数。

我找到了{{status_code}}和{{status_text}}个变量,但找不到类似的东西来解决我的问题。

P.S.我已经在使用自定义错误页面。我只是想给用户特定的错误解释。

Thnx。

回答

4

默认情况下,Symfony使用showActionSymfony\Bundle\TwigBundle\Controller\ExceptionController来呈现错误页面。在Symfony的2.3的实现是这样的:

public function showAction(Request $request, FlattenException $exception, DebugLoggerInterface $logger = null, $_format = 'html') 
{ 
    $currentContent = $this->getAndCleanOutputBuffering($request->headers->get('X-Php-Ob-Level', -1)); 

    $code = $exception->getStatusCode(); 

    return new Response($this->twig->render(
     $this->findTemplate($request, $_format, $code, $this->debug), 
     array(
      'status_code' => $code, 
      'status_text' => isset(Response::$statusTexts[$code]) ? Response::$statusTexts[$code] : '', 
      'exception'  => $exception, 
      'logger'   => $logger, 
      'currentContent' => $currentContent, 
     ) 
    )); 
} 

从那里,你可以看到,有'exception' => $exception传递给你的树枝模板。 $exception类型为Symfony\Component\HttpKernel\Exception\FlattenException,它是原始PHP异常的包装。

FlattenException::getMessage可能是你想要访问你的错误信息。有关更多信息,请参阅FlattenException API

+0

谢谢。你的回答不仅仅是我的问题。 – avkryukov

2

好的。 TWIG代码是

{{ exception.message|nl2br }} 
相关问题