使用Syfmony2,我创建了自定义错误模板,在我的情况下是
/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.');
我希望该消息显示在呈现的错误模板上。相反,它仅显示标准消息:
Internal Server Error
但是,当我在开发人员模式下运行时,它会显示正确的消息(但在Symfony2标准错误模板上)。为什么产品模式下的消息被隐藏?我要为谁写消息?对于开发日志?
(如何)也可以强制以产品模式在模板上显示消息?
最佳答案
您将需要制作一个自定义模板EventListener并注册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);
}
}
并且您将需要注册侦听器:
# 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
关于php - 如何将错误500消息传递给错误模板?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21932406/