Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I catch any 'not defined' route with Silex

Tags:

silex

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!

like image 358
Antonio Romero Oca Avatar asked Dec 01 '25 07:12

Antonio Romero Oca


1 Answers

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);
});
like image 52
Ralf Hertsch Avatar answered Dec 03 '25 23:12

Ralf Hertsch