Solved thread

This post is marked as solved. If you think the information contained on this thread must be part of the official documentation, please contribute submitting a pull request to its repository.

How to throw an exception with message to my view Ajax response or normal response?

I want do something like this:

throw new Exception("The system was deactivated.");

public function authAction() {
        $this->view->disable();
        if ($this->request->isPost() == true) {
            $this->request->getPost("user_name");
            $this->request->getPost("user_password");

            $o_user = \BtsUser::findFirst(array(
                        'userName = :userName: and password = :password:',
                        'bind' => array(
                            'userName' => $this->request->getPost("user_name"),
                            'password' => md5($this->request->getPost("user_password"))
                        )
            ));
            if ($o_user === false) {
                $this->flash->error("Incorrect credentials");
            } else {
                if (!$o_user->systemActive) {
                    throw new Exception("The system was deactivated.");  // HOW DO THIS IN PHALCON?
                }
                $this->session->set("user-name", "Michael");
                ...
            }
        }
    }

In your bootstrap or elsewhere before the call to App:handle() $eventsManager->attach("dispatch:beforeException", function (Event $event, Dispatcher $dispatcher, \Exception $exception) {}); and modify the response

edited Apr '15

i added,

 $di->set('dispatcher', function() {
        $dispatcher = new Dispatcher();
        $dispatcher->setDefaultNamespace("Frontend\Controllers");
        $eventsManager = new \Phalcon\Events\Manager();
        $eventsManager->attach("dispatch:beforeException", function (Event $event, Dispatcher $dispatcher, \Exception $exception) {});
        $dispatcher->setEventsManager($eventsManager);
        return $dispatcher;
    });

and in the controller:

    if (!$o_user->systemActive) {
                 throw new Exception("The system was deactivated.");
            }

but an error ocurr:

<br /><b>Fatal error</b>: Class 'Frontend\Controllers\Exception' not found in <b>/var/www/feedback/app/frontend/controllers/LoginController.php</b> on line ><b>33</b><br />



33.6k
Accepted
answer

It must be changed to:

if (!$o_user->systemActive) {
    throw new \Exception("The system was deactivated.");
}

Thanks Andres!