Symfony 2.如何在Twig模板中捕获Exception参数?

avk*_*kov 5 symfony symfony-2.3

我在控制器中抛出一些异常.

例如:

throw new AccessDeniedHttpException('some_text');
Run Code Online (Sandbox Code Playgroud)

我如何在我的Twig模板中捕获它的'some_text'参数.

我找到了{{status_code}}和{{status_text}}变量,但无法找到解决我问题的类似内容.

PS我已经使用自定义错误页面了.我只想给用户特定的错误解释.

日Thnx.

Syj*_*jin 4

默认情况下,Symfony 使用showActionofSymfony\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,
        )
    ));
}
Run Code Online (Sandbox Code Playgroud)

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

FlattenException::getMessage可能是您想要访问错误消息的内容。有关详细信息,请参阅FlattenException API 。