Symfony 2.如何捕捉Twig模板中的Exception参数



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

例如:

throw new AccessDeniedHttpException('some_text');

如何在我的Twig模板中捕捉它的‘some_text’参数?

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

附言:我已经在使用自定义错误页面了。我只是想给用户具体的错误解释。

Thnx。

默认情况下,Symfony使用SymfonyBundleTwigBundleControllerExceptionControllershowAction来呈现错误页面。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属于SymfonyComponentHttpKernelExceptionFlattenException类型,它是原始PHP异常的包装器。

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

好的。TWIG代码为

{{ exception.message|nl2br }}

相关内容

最新更新