Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Symfony 2. How to catch Exception parameter in Twig template?

I'm throwing some exception in my controller.

For example:

throw new AccessDeniedHttpException('some_text');

How can i catch it's 'some_text' parameter in my Twig template?

I found the {{ status_code }} and {{ status_text }} variables, but can't find something similar that solve my problem.

P.S. I'm already use custom error page. I just want give users specific error explanations.

Thnx.

like image 824
Andrey Kryukov Avatar asked Dec 18 '13 06:12

Andrey Kryukov


2 Answers

By default Symfony uses the showAction of Symfony\Bundle\TwigBundle\Controller\ExceptionController to render your error page. The Implementation in Symfony 2.3 is like:

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,
        )
    ));
}

From there you can see that there is 'exception' => $exception passed to your twig template. $exception is of type Symfony\Component\HttpKernel\Exception\FlattenException which is a wrapper for the original PHP Exception.

FlattenException::getMessage is probably what you want to access your error message. See FlattenException API for more Information.

like image 88
Syjin Avatar answered Sep 22 '22 14:09

Syjin


Ok. The TWIG code is

{{ exception.message|nl2br }}
like image 25
Andrey Kryukov Avatar answered Sep 19 '22 14:09

Andrey Kryukov