我在我的 Controller 中抛出了一些异常。
例如:
throw new AccessDeniedHttpException('some_text');
我怎样才能捕获它 'some_text' 我的 Twig 模板中的参数?
我找到了 {{ status_code }} 和 {{ status_text }} 变量,但找不到类似的东西来解决我的问题。
附注我已经在使用自定义错误页面。我只想给用户具体的错误解释。
谢谢。
最佳答案
默认情况下,Symfony 使用 showAction
的 Symfony\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
传递给你的 Twig 模板。 $exception
类型为 Symfony\Component\HttpKernel\Exception\FlattenException
这是原始 PHP 异常的包装器。FlattenException::getMessage
可能是您想要访问错误消息的内容。见 FlattenException API想要查询更多的信息。
关于Symfony 2. 如何在 Twig 模板中捕获异常参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20651029/