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

Need best/properly solution to catch managing action exceptions

I'm trying to implement wide exceptions mechanism to manage execution logic with minimum amount of code by throwing exceptions from Actions directly and managing them to special controllers. This exceptions can't be handled by extending Dispatcher::dispatch() couse they prevents all loop execution and forward() does not work properly after that. How can this behavior be done properly? For example here my (notworking) situation: Some REST api controller:

class RobotController extends ControllerMain{
    public function deleteRobotAction(){
        if($this->request->getPost('id', 'int',false)){
            //some stuff
        }else{
            throw new \Context\Exceptions\InvalidArgumentException(
                'some custom message for invalid argument types',
                \Context\ExceptionCodes::E_INVALID_INTEGER_VALUE //f.e. 100500 code
            );
        }
    }
}

and i would like to handle those exceptions with other universal ErrorsController:

class ErrorsController extends ControllerMain{
    public function error100500Action(){
        $message = $this->dispatcher->getParam('message');
        if(empty($message)){
            $message = 'Invalid arguments comes. Some of them must be an integer.'
        }
        return $message; //this cared by error View
    }
}

my first attempt was to manage them by extending \Phalcon\Mvc\Dispatcher particularly like this:

class Dispatcher extends \Phalcon\Mvc\Dispatcher{
    public function dispatch(){
        try{
            return parent::dispatch();
        }catch(\Context\Exception $e){
            $this->_throwDispatcherException($e->getMessage(), $e->getCode());
            return false;
        }
    }
}

and then i catch it in beforeException:

class SomeCustomDispatcherListener{
    public function beforeException($event, $dispatcher, $exception){
        //some other logic
        if($exception->getCode()>1000){
            $dispatcher->forward([
                'controller'=>'Errors', 
                'action'=>'error'.$exception->getCode(), 
                'params'=>['message'=>$exception->getMessage()]
            ]);
            return false; //preventing execution
        }
    }
}

But any atempts to filter and redirect my own exceptions make HTTP 404 Not Found response. Please consider my problem. I'll answer any additional questions if needed. Thanks.



98.9k

Starting from 1.2.1, a 'beforeException' listener can catch any exception produced when executing the controller/action (not just only the ones produced by the dispatcher).

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