简体   繁体   English

仅在自定义路由内时,Symfony错误页面

[英]Symfony error page only when inside the custom route

I am currently developing a re-usable bundle, wherein I am making additional routes (set inside routing.yml + loaded with Routing Loader mechanism). 我目前正在开发一个可重用的包,其中我正在制作其他路由(在routing.yml中设置并使用Routing Loader机制加载)。 All start with /admin (yes, this is an admin bundle). 全部以/admin开头(是的,这是一个管理包)。 I have currently my own 404 page in my web-application (the main one). 目前,我的网络应用程序(主要页面)中有我自己的404页面。 And I am trying to make that if the user is inside the admin bundle error he will see another error pages. 我试图使如果用户在管理员捆绑包错误内,他将看到另一个错误页面。

I made it with my own custom ExceptionListener (inside the custom admin bundle!) as following 我使用自己的自定义ExceptionListener (在自定义管理包内部!)做到了,如下所示

  class ExceptionListener
  {
     //...
     public function onKernelException(GetResponseForExceptionEvent $event)
     {
        $exception = $event->getException();
        $response = new Response();

        //...

        $response->setContent($this->templating->render($templateName, [
            'statusCode' => $response->getStatusCode(),
            'page' => $page
        ]));
        $event->setResponse($response);
     }
  }

and in the bundle's services.yml : 并在捆绑包的services.yml

 admin.exception_listener:
    class: ....\EventListener\ExceptionListener
    calls:
        - ["setTemplating", ["@templating"]]
        - ["setKernel", ["@kernel"]]
    tags:
       - { name: kernel.event_listener, event: kernel.exception }

Now it works fine, all custom bundle's error pages are shown. 现在工作正常,将显示所有自定义捆绑包的错误页面。 But they are being shown everywhere, even in the main application route fails. 但是它们无处不在,即使在主应用程序中也失败了。

How do I separate when to show application error pages and when to show custom-bundles? 如何区分何时显示应用程序错误页面和何时显示自定义包?

I'm going to assume that you want a different 404 page if the user attempts to visit a route that begins with /admin but doesn't exist. 如果用户尝试访问以/admin开头但不存在的路由,我将假设您想要一个不同的404页面。 You can do that in your onKernelException() method via: 您可以通过以下方法在onKernelException()方法中进行操作:

$request = $event->getRequest();

// check if request starts with /admin
if (substr($request->getRequestUri(), 0, strlen('/admin')) === '/admin') {
    // load admin 404 template
    $response->setContent(/* ... */);
} else {
    // load site 404 template
    $response->setContent(/* ... */);
}

$event->setResponse($response);

I also notice you're not explicitly checking for a 404 page, which you should probably do via: 我还注意到您没有明确检查404页面,您应该通过以下方式进行检查:

if ($exception instanceof NotFoundHttpException) {
    /* set your template response here */
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM