How to forward any wrong url request to 404 not found page

So when Phalcon cannot find the requested controller/action, he shows a message like : PhalconException: WrongController handler class cannot be loaded Or PhalconException: Action 'wrong' was not found on handler 'post'

How to forward any wrong url request to a 404 not found page (e.g: NotfoundController/indexAction) that I will show a cool 404 not found page, and not showing a PhalconException ...

Sorry for these questions, but I'm a new Phalcon user. Thank you.



34.6k

@sn0opr

You can insert in file inxex.php(app/public/index.php): ```bash try{} catch (Exception $e) { $response = new Phalcon\Http\Response();

//Set status code
$response->setStatusCode(404, "Not Found");

//Set the content of the response
$response->setContent("Sorry,My Website  in maintenance.");

//Send response to the client
$response->send();

} ```



14.3k

@duythien thank you for helping, But how to show the notfound controller (which I created for 404 pages app/controllers/notfoundController.php)

try this:

$di->set('dispatcher', function () {
    //Create/Get an EventManager
    $eventsManager = new \Phalcon\Events\Manager();
    //Attach a listener
    $eventsManager->attach("dispatch", function ($event, $dispatcher, $exception) {

        // controller or action doesn't exist
        if ($event->getType() == 'beforeException') {
            switch ($exception->getCode()) {
                case \Phalcon\Dispatcher::EXCEPTION_HANDLER_NOT_FOUND:
                case \Phalcon\Dispatcher::EXCEPTION_INVALID_HANDLER:
                case \Phalcon\Dispatcher::EXCEPTION_ACTION_NOT_FOUND:
                case \Phalcon\Dispatcher::EXCEPTION_INVALID_PARAMS:
                    $dispatcher->forward(array(
                        'controller' => 'notfound',
                        'action' => 'index'
                    ));

                    return false;
            }
        }
    });

    $dispatcher = new \Phalcon\Mvc\Dispatcher();

    $dispatcher->setEventsManager($eventsManager);

    return $dispatcher;
});