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: ```php 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::EINVALIDINTEGERVALUE //f.e. 100500 code ); } } } ``` and i would like to handle those exceptions with other universal ErrorsController: ```php 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: ```php 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: ```php 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.



83.0k

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).

http://docs.phalconphp.com/en/latest/reference/dispatching.html#handling-not-found-exceptions