Hi all,

I use this approach to handle exceptions thrown in Controller Actions. Nothing fancy here:

$eventsManager->attach('dispatch:beforeException', function($event, $dispatcher, $exception) {
    // Forward to Error controller:
    $dispatcher->forward([
        'controller' => 'error',
        'action' => 'oops',
        'params' => null,
    ]);
}

Everything works fine if an Exception is thrown inside Controller's Action, i.e. past this line:

https://github.com/phalcon/cphalcon/blob/master/phalcon/dispatcher.zep#L654

The problem is that if an Exception is thrown inside Controller's initialize(), then forwarding code above does not work (though it does get executed).

Looking at the code I see something that looks like an oversight to me. This is the code that handles Exception in the named action:

try {
    // We update the latest value produced by the latest handler
    let this->_returnedValue = this->callActionMethod(handler, actionMethod, params);
} catch \Exception, e {
    if this->{"_handleException"}(e) === false {
        if this->_finished === false {
            continue;
        }
    } else {
        throw e;
    }
}

As you can see, an Exception is caught and _handleException is fired inside the dispatch loop, thus giving a chance to forward() to affect execution in subsequent iteration.

And this is how Controller's initialize is called:

if wasFresh === true {
    if method_exists(handler, "initialize") {
        handler->initialize();
    }
    ...
}

So, if an Exception is thrown in initialize, the error bubbles up and out of the dispatch loop.

So, shouldn't there be a try\catch around the initialize() call as well?

Thanks!

EDIT: Opened this ticket.