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

Throw an Exception, convert it to Flash Message and render a page

Inside a model, validation code

...
public function set($price)
{
    if($price > 100) throw new \ValidationException('Invalid Price');

    $this->price = $price;
    return $this;
}

This exception will appear in screeen, an only it. How can we save this message into Flash Service and render this page?

edited Apr '15

Do you mean perhaps something like that?

...
public function set($price)
{
    if($price > 100) {
        throw new \ValidationException('Invalid Price');
        $this->getDI()->getShared("flash")->notice("Invalid price");
    }
    $this->price = $price;
    return $this;
}

Add a try/catch in the controller:

try {
    $model->set(100);
} catch (\Exception $e) {
    $this->flash->error($e->getException());
}

This will bahave like a normal exception. The second line will not be executed because an exceptionwas raised before.

Do you mean perhaps something like that?

...
public function set($price)
{
   if($price > 100) {
      throw new \ValidationException('Invalid Price');
      $this->getDI()->getShared("flash")->notice("Invalid price");
  }
   $this->price = $price;
   return $this;
}

Sounds good, but not DRY. It's not good to put try/catch clock in every validation.

I may put catch block in main application try/catch:

try {
    # All Phalcon code 
    ...
    throw new \ValidationException('Invalide price value')
    ....
} catch (\Phalcon\Exception $e) {
    ...
} catch (\ValidationException $e) {
    DI::getDefault()->get('flash')->error($e->getException());
}

What do you think?

Add a try/catch in the controller:

try {
  $model->set(100);
} catch (\Exception $e) {
   $this->flash->error($e->getException());
}

any help with this problem? i have this code:

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.");
                }
                $this->session->set("user-name", "Michael");
                ...
            }
        }
    }

Something like that? help!