After posting a response in the RESTful API thread showing a pattern I use to handle updates, I got a bit self-conscious about my use of Exceptions for handling action execution. I typically use exceptions to log errors and relay friendly/helpful messages to the end user when something goes wrong.
For example, I use a special ValidationException class to 1) Decide whether to display a flash message to users performing a CRUD operation, and 2) to track which models and attributes are confusing my end users (by generating a lot of validation exceptions).
I’ve attached a code example below. My basic question is, does my code look horrible? What are the drawbacks to this method? I generally work in an isolated developer environment (small firm) so I don’t get a lot of (read: any) feedback on style. All feedback is appreciated!
public function ActionUpdate($id) {
$customer = Customer::model()->findByPk($id);
if ($customer===null)
throw new CHttpException(404, "Customer #{$id} was not found in the database");
elseif (!Yii::app()->user->checkAccess('Customer.update', array('modelId' =>$id)))
throw new CHttpException(403, "You are not authorized to update customer #{$id}");
if (isset($_POST['Customer'])) {
$customer->setAttributes($_POST['Customer']);
try {
if (!$customer->validate())
throw new ValidationException($customer);
elseif (!$customer->save(false))
throw new SaveException($customer);
Yii::app()->user->setFlash("success", "Hooray! Customer #{$id} updated");
$this->refresh();
} catch (ValidationException $e) {
Yii::app()->user->setFlash("warning", "Oh no, you entered bad data");
} catch (SaveException $e) {
Yii::app()->user->setFlash("error", "Oh dear, the application failed!");
}
}
$this->render('update', array('customerModel' =>$customer));
}