GenericErrorHandler.php 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. <?php
  2. namespace demo\Errors;
  3. use Silex\Application;
  4. use Symfony\Component\HttpFoundation\Request;
  5. use Symfony\Component\HttpFoundation\Response;
  6. class GenericErrorHandler {
  7. /**
  8. * @var \Silex\Application
  9. */
  10. protected $app;
  11. public function __construct(Application $app) {
  12. $this->app = $app;
  13. }
  14. /* Custom error handlers registered with error() take precedence over the
  15. built-in error handler provider by Silex, but the formatted error messages it
  16. provides can be accessed in debug mode by returning based on $app['debug']
  17. like this.
  18. */
  19. public function __invoke(\Exception $e, Request $request, $code) {
  20. // Use the default handler in debug mode.
  21. if ($this->app['debug']) {
  22. return;
  23. }
  24. // Use our error formats otherwise.
  25. // 404.html, or 40x.html, or 4xx.html, or error.html
  26. $templates = [
  27. 'errors/' . $code . '.html.twig',
  28. 'errors/' . substr($code, 0, 2) . 'x.html.twig',
  29. 'errors/' . substr($code, 0, 1) . 'xx.html.twig',
  30. 'errors/default.html.twig',
  31. ];
  32. /** @var \Twig_Environment $twig */
  33. $twig = $this->app['twig'];
  34. /** @var \Twig_Template $template */
  35. $template = $twig->resolveTemplate($templates);
  36. return new Response($template->render(['code' => $code . ' : ' . $e->getMessage()]));
  37. }
  38. }