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

Exception thrown in beforeDispatchLoop/beforeDispatch does not get caught in beforeException

I'm using latest phalcon version (2.0.6). The problem is as described - I throw an error in beforeDispatch and expect it to be served by the logic placed in beforeException

service.php

$eventsManager->attach('dispatch:beforeDispatchLoop', new Thrower());
$eventsManager->attach('dispatch:beforeException', new Catcher());

Thrower.php

class Thrower extends Plugin
{
    public function beforeDispatchLoop(Event $event, Dispatcher $dispatcher)
    {
            throw new \Exception('Exception');
    }
}

Catcher.php

class Catcher extends Plugin
{
    public function beforeException(Event $event, Dispatcher $dispatcher)
    {
            // it doesnt get executed
            $dispatcher->forward(array('controller' => 'error', 'action' => 'error'));
    }
}

does phalcon support catching exceptions thrown inside beforeDispatchLoop/beforeDispatch? Or did I miss anything? exception thrown inside controllers/services get caught.

The documentation explains this behavior:

Only exceptions produced by the dispatcher and exceptions produced in the executed action are notified in the ‘beforeException’ events. Exceptions produced in listeners or controller events are redirected to the latest try/catch.

https://docs.phalcon.io/en/latest/reference/dispatching.html#handling-not-found-exceptions



1.7k

Thank you for the quick answer, however it's a bad news for me. Any chances that is going to be implemented? Or anyone could give me some tips how to get over this problem?

I have a plugin attached to every beforeDispatchLoop that looks for JWT token and performs the auth if found. It could also throw exceptions, when eg credentials are incorrect. This kind of exceptions are common, they are being thrown in various places within the app and they should be served one common way. It seems that I would have to duplicate the logic, but this is a solution I was trying to avoid