【问题标题】:Customize Exception Template by Bundle按 Bundle 自定义异常模板
【发布时间】:2014-01-24 07:29:20
【问题描述】:

如何通过bundle自定义异常?

示例:
我有两个捆绑包:BackendBundle 和 FrontEndBundle。我希望这两个包在抛出error 404 时由两个不同的模板处理。

我该怎么做?

我已经阅读了http://symfony.com/doc/current/cookbook/controller/error_pages.html,但仍然没有任何线索。

【问题讨论】:

  • 你是指错误页面还是异常页面(在dev中显示)?
  • @Pazi: 我的意思是我们thrown createNotFoundException()时的错误页面

标签: php symfony


【解决方案1】:

就像提到的cookbook article 一样,扩展TwigBundleSymfony\Bundle\TwigBundle\Controller\ExceptionController:findTemplate。在那里您可以决定(如果它不在调试中)显示哪个 404。

此示例假设您在/backend 下可以访问所有后端路由。根据您的需要更改它,或使用请求中的其他内容来确定您的后端 404。

namespace Acme\ErrorBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Templating\TemplateReference;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Bundle\TwigBundle\Controller\ExceptionController as BaseController;

/**
 * ExceptionController.
 */
class ExceptionController extends BaseController
{
    /**
     * @param Request $request
     * @param string  $format
     * @param integer $code       An HTTP response status code
     * @param Boolean $debug
     *
     * @return TemplateReference
     */
    protected function findTemplate(Request $request, $format, $code, $debug)
    {
        // find template for backend 404 errors
        if (!$this->debug && 404 == $code && false !== strpos($request->getPathInfo(), '/backend')) {
            $template = new TemplateReference('TwigBundle', 'Exception', 'backend404', $format, 'twig');
            if ($this->templateExists($template)) {
                return $template;
            }
        }

        // the parent method finds the error404.html.twig for the frontend
        return parent::findTemplate($request, $format, $code, $debug);
    }
}

另外提一下,ErrorBundle 必须继承自 TwigBundle。

【讨论】:

  • 是的,我已经读过了。但如何告诉 symfony。如果错误源来自 BackendBundle,那么使用后端包中的模板?你能给出一点sn-p代码吗?
  • 特别是我为您编写了代码,但通常很容易确定为您的用例覆盖哪种方法。
【解决方案2】:

您可以挂钩KernelEvents::EXCEPTION 事件并覆盖将发送到浏览器的响应。我为你写了一个简短的要点:

https://gist.github.com/bezhermoso/87716a9c72a1d12c5036

但是,$event->getRequest()->get('_controller') 显然会在出现 404 错误时返回 null。所以你必须考虑那个实例。

【讨论】:

  • 今晚会看看:D
  • @Pazi 那么你有什么建议呢?
  • @GusDeCooL:为了不丢失开发环境的默认错误报告,您可以随时查看$container->getParameter('kernel.environment'),而不要调用$event->setResponse(...)
  • 检查$event->getRequest()->isXmlHttpRequest()$event->isMasterRequest()
猜你喜欢
  • 2018-07-22
  • 2011-12-15
  • 2012-07-03
  • 2021-04-20
  • 1970-01-01
  • 2012-07-15
  • 2015-11-10
  • 2014-10-15
  • 2023-03-22
相关资源
最近更新 更多