2014-01-24 49 views
1

如何通過捆綁定製異常?通過捆綁定製異常模板

例如:
我有兩個捆綁:BackendBundle和FrontEndBundle。當我們拋出error 404時,我希望這兩個捆綁包由兩個不同的模板處理。

我怎麼能這樣做?

我看過http://symfony.com/doc/current/cookbook/controller/error_pages.html但還是沒有線索。

+0

你是指錯誤頁面還是異常頁面(在dev中顯示)? –

+0

@Pazi:我的意思是錯誤頁面,當我們拋出createNotFoundException()' – GusDeCooL

回答

0

您可以掛鉤到KernelEvents::EXCEPTION事件並覆蓋將發送到瀏覽器的響應。我寫了一個快速要點給你:

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

然而,$event->getRequest()->get('_controller')將在404錯誤返回null,效果顯着。所以你必須考慮這個例子。

+0

看看這個晚上:D – GusDeCooL

+0

這會攔截並炸掉正常的錯誤處理! –

+0

@Pazi那麼你會建議什麼呢? – GusDeCooL

1

就像在cookbook article提到的那樣,擴展TwigBundleSymfony\Bundle\TwigBundle\Controller\ExceptionController:findTemplate。在那裏你可以決定(如果它不在調試中)404顯示。

本示例假設您可以在/backend下訪問所有後端路由。將其更改爲您的需求,或使用請求中的其他內容來確定您的後端404s。

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繼承。

+0

是的,我讀過。但如何告訴symfony。如果錯誤來源來自BackendBundle,那麼使用來自後端包的模板?你可以給一點片段代碼如何呢? – GusDeCooL

+0

例外地,我爲您編寫了它,但通常很容易確定爲您的用例覆蓋哪種方法。 –

+0

感謝兄弟,我會測試你的代碼:D – GusDeCooL