如何通过Silex捕获任何“未定义”的路线

时间:2014-09-09 06:56:46

标签: silex

我在Silex中定义了几条路线,但我不知道如何捕捉不存在的路线。

例如:

$app->get('/category/{name}', 'Acme\Controller\Main::category');

我预计没有必要无限制地定义所有路线:

$app->get('/category/{name}', 'Acme\Controller\Main::notFound');
$app->get('/category/{name}/', 'Acme\Controller\Main::notFound');
$app->get('/category/{name}/{name2}', 'Acme\Controller\Main::notFound');
$app->get('/category/{name}/{name2}/', 'Acme\Controller\Main::notFound');
$app->get('/category/{name}/{name2}/{name3}', 'Acme\Controller\Main::notFound');
[...]

最优雅的解决方案是什么?

提前致谢!

1 个答案:

答案 0 :(得分:5)

您可以使用$app->error()捕获所有错误 - 另请参阅Silex Documentation

示例:

use Symfony\Component\HttpFoundation\Response;

$app->error(function (\Exception $e, $code) use ($app) {

  if ($app['debug']) {
    // in debug mode we want to get the regular error message
    return;
  }

  switch ($code) {
    case 404:
        $message = 'The requested page could not be found.';
        break;
    default:
        $message = 'We are sorry, but something went terribly wrong.';
  }

  return new Response($message);
});