2014-02-21 22 views
1

使用Syfmony2,我已创建自定义错误模板,在我的情况下,它是如何将错误500消息传递给我的错误模板?

/app/Resources/TwigBundle/views/Exception/error.html.twig 

,看起来在某种程度上是这样

<html> 
    </body> 
    <h1>ERROR {{ status_code }}</h1> 
    <p>{{ status_text }}</p> 
    </body> 
</html> 

当我现在在它的消息引发错误:

throw new Exception('There is something wrong in the state of Denkmark.'); 

我希望消息显示在呈现的错误模板上。相反,它只能说明一个标准的消息:

内部服务器错误

然而,当我在开发模式下运行它显示了正确的信息(但在Symfony2的标准错误模板)。为什么隐藏prod模式的消息?我为谁写信息?对于开发日志?

(How)我可以强制在prod模式下在我的模板上显示消息吗?

+0

你是什么意思与 “标准错误模板”?进入日志? – DonCallisto

+0

不,我的意思是这个开发与甜美的黑色怪物和绿色泡沫的错误模板:http://i.stack.imgur.com/6TzhM.png –

回答

1

你会NEDD做一个自定义模板,事件监听和注册EventListener:

// src/Acme/DemoBundle/EventListener/AcmeExceptionListener.php 
namespace Acme\DemoBundle\EventListener; 

use Symfony\Component\HttpKernel\Event\GetResponseForExceptionEvent; 
use Symfony\Component\HttpFoundation\Response; 
use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface; 

class AcmeExceptionListener 
{ 
    public function onKernelException(GetResponseForExceptionEvent $event) 
    { 
    // You get the exception object from the received event 
    $exception = $event->getException(); 
    $message = sprintf(
     'My Error says: %s with code: %s', 
     $exception->getMessage(), 
     $exception->getCode() 
    ); 

    // Customize your response object to display the exception details 
    $response = new Response(); 
    $response->setContent($message); 

    // HttpExceptionInterface is a special type of exception that 
    // holds status code and header details 
    if ($exception instanceof HttpExceptionInterface) { 
     $response->setStatusCode($exception->getStatusCode()); 
     $response->headers->replace($exception->getHeaders()); 
    } else { 
     $response->setStatusCode(Response::HTTP_INTERNAL_SERVER_ERROR); 
    } 

    // Send the modified response object to the event 
    $event->setResponse($response); 
    } 
} 

,你将需要注册listenter:

# app/config/config.yml 
services: 
    kernel.listener.your_listener_name: 
     class: Acme\DemoBundle\EventListener\AcmeExceptionListener 
     tags: 
      - { name: kernel.event_listener, event: kernel.exception, method:  
onKernelException } 

来源: http://symfony.com/doc/current/cookbook/service_container/event_listener.html

2

此行为是正确的,因为Exception可能包含一些“内部”信息,并且在生产环境中不应显示这些信息。

你可以做的是costumize 404页,或使用自己的逻辑在发生异常时,显示的东西,但你不能依赖Symfony2的标准逻辑,因为它不是你的

对于costumize 404页兼容,你应该把这里您自己的错误页面app/Resources/TwigBundle/views/Exception/error404.html.twig

为了你自己的逻辑ovveride默认模板:只需使用event listener/subscriber,将在一些例外

呈现页面
+0

呃好吧,我已经假设了这样的事情。那意味着我应该创建自己的例外?可能使用我自己的错误代码,例如在460s不使用现有的和写一个错误460.html.twig与静态错误信息? –

+0

@GottliebNotschnabel:看看我的更新 – DonCallisto

+0

我不是在谈论404错误,我已经有了'error404.html.twig'。我正在寻找错误500s。 –

相关问题