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.
<?php
$app = new \Slim\Slim();
$app->notFound(function () use ($app) {
$app->render('404.html');
});
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.
<?php
$app = new \Slim\Slim();
$app->get('/hello/:name', function ($name) use ($app) {
if ( $name === 'Waldo' ) {
$app->notFound();
} else {
echo "Hello, $name";
}
});