Symfony php 自定义异常控制器不工作
Symfony php Custom exception controller not working
我正在尝试在 php Symfony 4 中创建一个自定义异常控制器。本质上我想要做的是有一个默认路由,当没有其他路由匹配时被调用。
我正在尝试遵循此处的建议:
https://symfony.com/doc/current/controller/error_pages.html#custom-exception-controller
我在 configs>>pacakges:
中创建了 twig.yaml 文件
twig:
exception_controller: App\Controller\ExceptionController::showException
我还创建了 ExceptionController class:
<?php
namespace App\Controller;
use Symfony\Component\HttpFoundation\Response;
class ExceptionController
{
public function showException()
{
$response = new Response();
$response->setContent("Some random text");
$response->headers->set('Content-Type', 'text/plain');
$response->headers->set('Access-Control-Allow-Origin', '*');
$response->setStatusCode(200);
return $response;
}
}
当我访问一个不存在的 url 时,我希望看到文本“一些随机文本”,但我得到的是默认的 symfony 未找到页面:
知道我做错了什么吗?
您是否尝试过使用 routing 作为路由? Rooting
您提到您在 configs/packages
下创建了一个 twig.yaml
。
两件事:
- 这应该是
config
,而不是configs
twig.yaml
应该已经存在了,没有必要创建这个文件。
我怀疑如果你创建了这个文件,你在错误的地方创建了一个文件,Symfony 没有接收你的配置更改。相反,将您的配置更改添加到 config/packages
.
下的现有 twig.yaml
文件
将自定义 exception_controller
路径添加到此现有(假定默认)twig.yaml
后,它应该如下所示:
twig:
default_path: '%kernel.project_dir%/templates'
debug: '%kernel.debug%'
strict_variables: '%kernel.debug%'
exception_controller: App\Controller\ExceptionController::showException
我用全新安装测试了它,它按预期工作。
希望这对您有所帮助:)
您的方法应该被称为 showException
,而不是您在 twig.exception_controller
配置中定义的 endpoint
。
我正在尝试在 php Symfony 4 中创建一个自定义异常控制器。本质上我想要做的是有一个默认路由,当没有其他路由匹配时被调用。
我正在尝试遵循此处的建议: https://symfony.com/doc/current/controller/error_pages.html#custom-exception-controller
我在 configs>>pacakges:
中创建了 twig.yaml 文件twig:
exception_controller: App\Controller\ExceptionController::showException
我还创建了 ExceptionController class:
<?php
namespace App\Controller;
use Symfony\Component\HttpFoundation\Response;
class ExceptionController
{
public function showException()
{
$response = new Response();
$response->setContent("Some random text");
$response->headers->set('Content-Type', 'text/plain');
$response->headers->set('Access-Control-Allow-Origin', '*');
$response->setStatusCode(200);
return $response;
}
}
当我访问一个不存在的 url 时,我希望看到文本“一些随机文本”,但我得到的是默认的 symfony 未找到页面:
知道我做错了什么吗?
您是否尝试过使用 routing 作为路由? Rooting
您提到您在 configs/packages
下创建了一个 twig.yaml
。
两件事:
- 这应该是
config
,而不是configs
twig.yaml
应该已经存在了,没有必要创建这个文件。
我怀疑如果你创建了这个文件,你在错误的地方创建了一个文件,Symfony 没有接收你的配置更改。相反,将您的配置更改添加到 config/packages
.
twig.yaml
文件
将自定义 exception_controller
路径添加到此现有(假定默认)twig.yaml
后,它应该如下所示:
twig:
default_path: '%kernel.project_dir%/templates'
debug: '%kernel.debug%'
strict_variables: '%kernel.debug%'
exception_controller: App\Controller\ExceptionController::showException
我用全新安装测试了它,它按预期工作。
希望这对您有所帮助:)
您的方法应该被称为 showException
,而不是您在 twig.exception_controller
配置中定义的 endpoint
。