We have moved our forum to GitHub Discussions. For questions about Phalcon v3/v4/v5 you can visit here and for Phalcon v6 here.

Undefined class constant 'EXCEPTION_HANDLER_NOT_FOUND'

<?php
use Phalcon\Events\Event;
use Phalcon\Dispatcher;
use Phalcon\Mvc\Dispatcher\Exception as DispatcherException;

$evManager->attach(
            'dispatch:beforeException',
            function($event, $dispatcher, $exception)
            {   
                switch ($exception->getCode()) {
                    case MvcDispatcher::EXCEPTION_HANDLER_NOT_FOUND:
                    case MvcDispatcher::EXCEPTION_ACTION_NOT_FOUND:
                        $MvcDispatcher->forward(
                            array(
                                'namespace' => 'Controllers',
                                'controller' => 'No',
                                'action'     => 'index',
                            )
                        );
                        return false;
                }
            }
        );

Get error Undefined class constant 'EXCEPTION_HANDLER_NOT_FOUND'



1.3k
Accepted
answer

If none of the routes, specified in the router, match, you can define a 404 controller/action by using the notFound method.

<?php

$router->notFound(
    [
        'controller' => 'index',
        'action'     => 'fourOhFour',
    ]
);

NOTE: This will only work if the router was created without default routes: $router = Phalcon\Mvc\Router(false);

I guess this issue happened after an upgrade to 4.x from 3.x

The exceptions constants have been moved from Phalcon\Dispatcher. Now they are available here Phalcon\Dispatcher\Exception.

If you want to keep the logic of your initial implementation you can use it as following. (I'm modifying your code


use Phalcon\Events\Event;
use Phalcon\Dispatcher;
use Phalcon\Dispatcher\Exception as DispatcherException;

$evManager->attach(
            'dispatch:beforeException',
            function($event, $dispatcher, $exception)
            {   
                switch ($exception->getCode()) {
                    case DispatcherException::EXCEPTION_HANDLER_NOT_FOUND:
                    case DispatcherException::EXCEPTION_ACTION_NOT_FOUND:
                        $dispatcher->forward(
                            array(
                                'namespace' => 'Controllers',
                                'controller' => 'No',
                                'action'     => 'index',
                            )
                        );
                        return false;
                }
            }
        );

I was facing the same issue, and that's how i managed to fix it. This information have been found in the doc.

https://docs.phalcon.io/4.0/fr-fr/api/phalcon_dispatcher#dispatcher-exception