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

Redirect global exceptions to a controller/action

try {
    $application = new \Phalcon\Mvc\Application($di);

    ....

    echo $application->handle()->getContent();

} catch (\Exception $e) {
    $traza=str_replace("\n",'<br>',$e->getTraceAsString());
    $application->dispatcher->forward([
      'controller'=>'error',
      'action'=>'error500',
      'params'=>[$e->getMessage(),$traza]
    ]);
}

I wrote this code snippet to catch global exceptions and redirect them to error::error500(), but not works. What I'm doing bad?

Thanks!!

That might not work because the exception might have been generated in the dispatcher. If the dispatcher threw an exception, it can't then be used to forward the user.

In my opinion, handling exceptions like this could be treated as a one-off. That is, you don't need to build a robust system around handling execptions. If you've got some session-based error handling, you could set an error like "An exception has been encountered", then redirect the user back to your homepage (using the vanilla PHP header() function)



298
edited Nov '19

I answered myself.

I put this exception block and all works fine, but I'll happy if someone knows a more optimal solution.

$traza=str_replace("\n",'<br>',$e->getTraceAsString());
$application->dispatcher->forward([
  'controller'=>'error',
  'action'=>'error500',
  'params'=>[$e->getMessage(),$traza]
]);
$application->dispatcher->dispatch();
$application->response->send();
$application->view->start();
$application->view->render('error','error500');
$application->view->finish();
echo $application->view->getContent();