Browse Source

[FrameworkBundle] added a simple way to customize errors according to the HTTP status code

Fabien Potencier 14 years ago
parent
commit
514b47c6d4
1 changed files with 29 additions and 12 deletions
  1. 29 12
      src/Symfony/Bundle/FrameworkBundle/Controller/ExceptionController.php

+ 29 - 12
src/Symfony/Bundle/FrameworkBundle/Controller/ExceptionController.php

@@ -45,21 +45,11 @@ class ExceptionController extends ContainerAware
             $currentContent .= ob_get_clean();
         }
 
-        $name = $this->container->get('kernel')->isDebug() ? 'exception' : 'error';
-        if ($this->container->get('kernel')->isDebug() && 'html' == $format) {
-            $name = 'exception_full';
-        }
-        $template = 'FrameworkBundle:Exception:'.$name.'.'.$format.'.twig';
-
         $templating = $this->container->get('templating');
-        if (!$templating->exists($template)) {
-            $this->container->get('request')->setRequestFormat('html');
-            $template = 'FrameworkBundle:Exception:'.$name.'.html.twig';
-        }
-
         $code = $exception->getStatusCode();
+
         $response = $templating->renderResponse(
-            $template,
+            $this->findTemplate($templating, $format, $code, $this->container->get('kernel')->isDebug()),
             array(
                 'status_code'    => $code,
                 'status_text'    => Response::$statusTexts[$code],
@@ -74,4 +64,31 @@ class ExceptionController extends ContainerAware
 
         return $response;
     }
+
+    protected function findTemplate($templating, $format, $code, $debug)
+    {
+        $name = $debug ? 'exception' : 'error';
+        if ($debug && 'html' == $format) {
+            $name = 'exception_full';
+        }
+
+        // when not in debug, try to find a template for the specific HTTP status code and format
+        if (!$debug) {
+            $template = 'FrameworkBundle:Exception:'.$name.$code.'.'.$format.'.twig';
+            if ($templating->exists($template)) {
+                return $template;
+            }
+        }
+
+        // try to find a template for the given format
+        $template = 'FrameworkBundle:Exception:'.$name.'.'.$format.'.twig';
+        if ($templating->exists($template)) {
+            return $template;
+        }
+
+        // default to a generic HTML exception
+        $this->container->get('request')->setRequestFormat('html');
+
+        return 'FrameworkBundle:Exception:'.$name.'.html.twig';
+    }
 }