symfony - 仅适用于 PROD 环境的自定义错误页面?

标签 symfony

如何仅为 PROD 环境设置自定义错误页面?我想显示用于生产的自定义环境,但显示普通环境,但开发环境除外。

有什么想法吗?

最佳答案

我遇到了同样的问题,解决方案非常简单。您必须修改参数twig.exception_listener.contoller以将错误页面的渲染重定向到您自己的 Controller ,这可能会扩展原始Twig异常 Controller 。

示例(YourBundle/Resources/config/services.xml):

<parameter key="twig.exception_listener.controller">YourBundle\Controller\ExceptionController::showAction</parameter>

然后,您必须使用 showAction 方法创建自己的 ExceptionController,检查环境并执行您想要执行的操作,或者将请求传递给 parent::showAction()

namespace YourBundle\Controller;

use Symfony\Bundle\TwigBundle\Controller\ExceptionController as BaseExceptionController;
use Symfony\Bundle\FrameworkBundle\Templating\TemplateReference;
use Symfony\Component\HttpKernel\Exception\FlattenException;
use Symfony\Component\HttpKernel\Log\DebugLoggerInterface;
use Symfony\Component\HttpFoundation\Response;

class ExceptionController extends BaseExceptionController {

    public function showAction(FlattenException $exception, DebugLoggerInterface $logger = null, $format = 'html') {
        $kernel = $this->container->get('kernel');

        if ($kernel->getEnvironment() == 'prod') {
            $request = $this->container->get('request');
            $request->setRequestFormat($format);

            $templating = $this->container->get('templating');
            $code = $exception->getStatusCode();

            $template = new TemplateReference('YourBundle', 'Exception', 'errorpage', $format, 'twig');
            if ($templating->exists($template)) {
                    $response = $templating->renderResponse($template, array(
                        'status_code' => $code,
                        'message_code' => 'error_' . $code,
                        'status_text' => Response::$statusTexts[$code],
                        'requested_url' => $request->getUri(),
                ));

                $response->setStatusCode($code);
                $response->headers->replace($exception->getHeaders());

                return $response;
            }
        }

        return parent::showAction($exception, $logger, $format);
    }
}

请注意 errorpage.html.twig 中的错误,因为 twig 处理中的异常不会像平常一样处理。

关于symfony - 仅适用于 PROD 环境的自定义错误页面?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9472482/

相关文章:

php - 从学说和 native mysql 查询中获取最后插入的 ID

symfony - 为什么无法在 CompilerPass 中注入(inject) logger 服务?

php - 将自定义实体存储库与 FOSUserBundle 结合使用

php - 索纳塔管理仪表板 : configure actions per entity

ubuntu - Symfony2 在 Ubuntu 虚拟机上运行缓慢

php - 向 Symfony 2 表单元素添加错误

Symfony 信使和邮件程序 : how to add a binding_key?

doctrine-orm - Symfony Doctrine 实体管理器和存储库

php - Symfony 软删除

symfony - 使用 Behat 3 测试 Symfony2 电子邮件