php - 如何将错误500消息传递给错误模板?

标签 php symfony exception error-handling

使用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/

相关文章:

java - Executor、线程池的捕获异常

php - 无法将 PHP 嵌入到 CSS 样式的单选按钮中以填充表单

php - 在 Symfony2 中,\DateTime 是什么意思?

python - 对于 python 有没有办法从发生异常的上下文中打印变量范围?

mysql - Doctrine - 查询构建器使用数组设置参数(嵌套/多个值)

Symfony2 : How to get user Object inside controller when using FOSUserBundle?

java - 使异常默认执行某些操作

php - URL 转发时不会加载 JS/CSS 文件

PHP 分解 mysql 行并获取大小

javascript - yii2 中的 Yii2 Ajax 请求