如何通過捆綁定製異常?通過捆綁定製異常模板
例如:
我有兩個捆綁:BackendBundle和FrontEndBundle。當我們拋出error 404
時,我希望這兩個捆綁包由兩個不同的模板處理。
我怎麼能這樣做?
我看過http://symfony.com/doc/current/cookbook/controller/error_pages.html但還是沒有線索。
如何通過捆綁定製異常?通過捆綁定製異常模板
例如:
我有兩個捆綁:BackendBundle和FrontEndBundle。當我們拋出error 404
時,我希望這兩個捆綁包由兩個不同的模板處理。
我怎麼能這樣做?
我看過http://symfony.com/doc/current/cookbook/controller/error_pages.html但還是沒有線索。
您可以掛鉤到KernelEvents::EXCEPTION
事件並覆蓋將發送到瀏覽器的響應。我寫了一個快速要點給你:
https://gist.github.com/bezhermoso/87716a9c72a1d12c5036
然而,$event->getRequest()->get('_controller')
將在404錯誤返回null
,效果顯着。所以你必須考慮這個例子。
就像在cookbook article提到的那樣,擴展TwigBundle
和Symfony\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繼承。
你是指錯誤頁面還是異常頁面(在dev中顯示)? –
@Pazi:我的意思是錯誤頁面,當我們拋出createNotFoundException()' – GusDeCooL