自定义错误页面InvalidArgumentException Symfony2

时间:2015-04-05 15:39:15

标签: symfony

我正在尝试在symfony2中生成自定义错误页面: 我正在关注这个tuto。 然而它告诉我这个:

InvalidArgumentException in YamlFileLoader.php line 145: A service definition must be an array or a string starting with "@" but NULL found for service "kernel.listener.allotaxi_exception_listener" in services.yml. Check your YAML syntax.

我的services.yml:

services:
    kernel.listener.allotaxi_exception_listener:
    class: AlloTaxi\AlloTaxiBundle\Listener\ExceptionListener
    arguments: [@templating, @kernel]
    tags:
        - { name: kernel.event_listener, event: kernel.exception, method: onKernelException }

ExceptionListener.php:

namespace AlloTaxi\AlloTaxiBundle\Listener;
use Symfony\Component\HttpKernel\Event\GetResponseForExceptionEvent;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface;

use Symfony\Bundle\FrameworkBundle\Templating\EngineInterface;
class ExceptionListener {

    protected $templating;
    protected $kernel;

    public function __construct(EngineInterface $templating, $kernel)
    {
        $this->templating = $templating;
        $this->kernel = $kernel;
        }

        public function onKernelException(GetResponseForExceptionEvent $event)
        {
        // provide the better way to display a enhanced error page only in prod environment, if you want
        if ('prod' == $this->kernel->getEnvironment()) {
        // exception object
        $exception = $event->getException();

        // new Response object
        $response = new Response();

        // set response content
        $response->setContent(
            // create you custom template AcmeFooBundle:Exception:exception.html.twig
            $this->templating->render(
                'AlloTaxiBundle:Exception:error.html.twig',
                array('exception' => $exception)
            )
        );

        // 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(500);
        }

        // set the new $response object to the $event
        $event->setResponse($response);
    }
}
}

知道它会是什么?我完全跟着他去那里。

1 个答案:

答案 0 :(得分:1)

services:
    kernel.listener.allotaxi_exception_listener:
        class: AlloTaxi\AlloTaxiBundle\Listener\ExceptionListener
        arguments: [@templating, @kernel]
        tags:
        - { name: kernel.event_listener, event: kernel.exception, method: onKernelException }

通过查看问题中发布的services.yml文件,您错过了“class”,“arguments”&的缩进级别。 “标签”。它们看起来与您的服务名称“kernel.listener.allotaxi_exception_listener”的级别相同

查看上面的服务定义,注意服务名称和类之间的缩进,参数和&标签

在处理yml文件时,需要注意正确的层次结构