I have defined several routes in Silex, but I don't know how to catch not existing routes.
For example:
$app->get('/category/{name}', 'Acme\Controller\Main::category');
I expect it is not necessary to defines all routes ad infinitum:
$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');
[...]
What is the most elegant solution for that?
Thanks in advance!
You can catch all errors using $app->error() - see also Silex Documentation.
Example:
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);
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With