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

beforeExecuteRoute not firing properly

Hi all,

I'm triying to catch a beforeException when an action does not exists but it does fire before the beforeExecuteRoute that I have at the controller.

this is the code:

abstract class ControllerWeb extends Controller 
{
    public function beforeExecuteRoute(Dispatcher $dispatcher)
    {
          die("beforeExecuteRoute");
    }
}

class PagePlugin extends Plugin
{
    public function beforeException(Event $event, Dispatcher $dispatcher, \Exception $exception = null)
    { 
          die("beforeException");
    }

}

When I try to access to a non defined action I want my beforeException to fire, but AFTER the beforeExecuteRoute The beforeExecuteRoute fires properly on other cases, but when the Action is not defined the beforeException fires first. Is this the normal behaviour? As I see it the beforeExecuteRoute must fire first since we don't care yet about the action or controller exceptions, right?

I see:

beforeExecuteRoute: Triggered before executing the controller/action method. At this point the dispatcher has been initialized the controller and know if the action exist.

it does fire the exception first :(

Use beforeException:

class NotFound extends Plugin {

    /**
     * This action is executed before execute any action in the application
     *
     * @param Event $event
     * @param MvcDispatcher $dispatcher
     * @param Exception $exception
     * @return bool
     */
    public function beforeException(Event $event, MvcDispatcher $dispatcher, Exception $exception)
    {
        if ($exception instanceof DispatcherException) {
            switch ($exception->getCode()) {
                case Dispatcher::EXCEPTION_HANDLER_NOT_FOUND:
                case Dispatcher::EXCEPTION_ACTION_NOT_FOUND:
                    $dispatcher->forward(array(
                        'controller' => 'error',
                        'action' => 'show404'
                    ));
                    return false;
            }
        }
        /*
        if($this->config->application->debug) {
            return true;
        }
        */
        $dispatcher->forward(array(
            'controller'=> 'error',
            'action'    => 'show500',
            'params'    => [$exception],
        ));
        return false;
    }

}
/// services.php
        $eventsManager->attach('dispatch:beforeException', new NotFoundPlugin);
        $dispatcher->setEventsManager($eventsManager);