类CustomExceptionController不存在Symfony4

时间:2019-03-17 14:56:31

标签: symfony twig yaml

对于一个应用程序,我想在symfony 4中创建一个自定义错误404页面。 但是Symfony在遵循了文档之后,在所有页面中都将其删除:

Invalid service "App\Controller\CustomExceptionController": class "App\Controller\CustomExceptionController" does not exist.

当我拥有创建自定义错误页面所需的所有插件时,我不知道为什么他找不到此类。

error404.html.twig

{% extends 'base.html.twig' %}

{% block main %}
    <h1>Page not found</h1>

    <p>
        The requested page couldn't be located. Checkout for any URL
        misspelling or <a href="{{ path('home') }}">return to the homepage</a>.
    </p>
{% endblock %}

services.yaml

# This file is the entry point to configure your own services.
# Files in the packages/ subdirectory configure your dependencies.

# Put parameters here that don't need to change on each machine where the app is deployed
# https://symfony.com/doc/current/best_practices/configuration.html#application-related-configuration
parameters:
    locale: 'fr'

services:
    # default configuration for services in *this* file
    _defaults:
        autowire: true      # Automatically injects dependencies in your services.
        autoconfigure: true # Automatically registers your services as commands, event subscribers, etc.

    # makes classes in src/ available to be used as services
    # this creates a service per class whose id is the fully-qualified class name
    App\:
        resource: '../src/*'
        exclude: '../src/{DependencyInjection,Entity,Migrations,Tests,Kernel.php}'

    # controllers are imported separately to make sure services can be injected
    # as action arguments even if you don't extend any base controller class
    App\Controller\:
        resource: '../src/Controller'
        tags: ['controller.service_arguments']

    # add more service definitions when explicit configuration is needed
    # please note that last definitions always *replace* previous ones

    App\Controller\CustomExceptionController:
        public: true
        arguments:
            $debug: '%kernel.debug%'

twig.yaml

twig:
    default_path: '%kernel.project_dir%/templates'
    debug: '%kernel.debug%'
    strict_variables: '%kernel.debug%'
    exception_controller: App\Controller\ExceptionController::showException

错误页面

1 个答案:

答案 0 :(得分:1)

如果您只想修改404错误页面的模板,则不必创建新的异常控制器,只需按照here中所述覆盖错误模板error404.html.twig。这是调整任何错误页面的最简单方法。

但是,如果您希望自定义逻辑生成错误页面,则必须编写自己的异常控制器,即,您必须实际实现类App\Controller\CustomExceptionController,而不仅仅是在yaml配置中指向它。最简单的方法是扩展默认的ExceptionController并覆盖showAction()和/或findTemplate()方法。然后在树枝配置中指向您的控制器:

# twig.yaml
twig:
    [...] 
    exception_controller: App\Controller\CustomExceptionController::showAction