404 Errors

It is an inevitability that someone will request a page that does not exist. The Slim application lets you easilydefine a custom Not Found handler with the Slim application’s notFound() method. The Not Found handler will beinvoked when a matching route is not found for the current HTTP request. This method acts as both a getter and a setter.

Set not found handler

If you invoke the Slim application’s notFound() method and specify a callable object as its first and onlyargument, this method will register the callable object as the Not Found handler. However, the registered handlerwill not be invoked.

  1. <?php
  2. $app = new \Slim\Slim();
  3. $app->notFound(function () use ($app) {
  4. $app->render('404.html');
  5. });

Invoke not found handler

If you invoke the Slim application’s notFound() method without any arguments, this method will invoke thepreviously registered Not Found handler.

  1. <?php
  2. $app = new \Slim\Slim();
  3. $app->get('/hello/:name', function ($name) use ($app) {
  4. if ( $name === 'Waldo' ) {
  5. $app->notFound();
  6. } else {
  7. echo "Hello, $name";
  8. }
  9. });