gpt4 book ai didi

silex - 如何使用 Silex 捕获任何 'not defined' 路由

转载 作者:行者123 更新时间:2023-12-01 10:46:09 25 4
gpt4 key购买 nike

我在 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');
[...]

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

提前致谢!

最佳答案

您可以使用 $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);
});

关于silex - 如何使用 Silex 捕获任何 'not defined' 路由,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25738381/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com