How can I throw a 404 error code when a route does not exist?
In phalcon after you set up your routing information - is there a way to check to see if a route coming in (from the user) matches any of the routes in your routes list? Then, if the route does not exist, throw a 404 error.
You can use something like this:
public function main()
{
try {
$this->_registerServices();
$this->registerModules(self::$modules);
$this->handle()->send();
} catch (Exception $e) {
// TODO log exception
// remove view contents from buffer
ob_clean();
$errorCode = 500;
$errorView = 'errors/500_error.phtml';
switch (true) {
// 401 UNAUTHORIZED
case $e->getCode() == 401:
$errorCode = 401;
$errorView = 'errors/401_unathorized.phtml';
break;
// 403 FORBIDDEN
case $e->getCode() == 403:
$errorCode = 403;
$errorView = 'errors/403_forbidden.phtml';
break;
// 404 NOT FOUND
case $e->getCode() == 404:
case ($e instanceof Phalcon\Mvc\View\Exception):
case ($e instanceof Phalcon\Mvc\Dispatcher\Exception):
$errorCode = 404;
$errorView = 'errors/404_not_found.phtml';
break;
}
// Get error view contents. Since we are including the view
// file here you can use PHP and local vars inside the error view.
ob_start();
include_once $errorView;
$contents = ob_get_contents();
ob_end_clean();
// send view to header
$response = $this->getDI()->getShared('response');
$response->resetHeaders()
->setStatusCode($errorCode, null)
->setContent($contents)
->send();
}
}
If you are using the Micro component you can use this:
$app->notFound(
function () use ($app) {
$app->response->setStatusCode(404, "Not Found")->sendHeaders();
echo 'This is crazy, but this page was not found!';
}
);
Of course you can use the suggestions that others posted regarding the .htaccess file, but above is how you do it in Phalcon without touching anything else.
There is also a new feature coming down the pipeline, regarding a default error handler that would process errors in Phalcon (or overriden if necessary).
Credits to Nesbert for the gist
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