How do you handle “catching” errors in a plugin service and return the error to the plugins controller?
To be more specific... I am sending an Ajax request to a controller, that controller is performing a few checks (is the user logged in for example, if not logged in - return a json response).
See the below controller
code:
public function actionMyController($elementId)
{
if ($this->notLoggedIn()) {
return;
}
}
protected function notLoggedIn()
{
if (!craft()->userSession) {
return $this->returnJson('You must be logged in!');
}
}
However, when those conditions are met the data is passed to the plugin service. In this case $elementId
and $userId
. Before creating the record, I'm performing additional checks on the data. When those checks fail, it should return additional JSON responses to the controller to display on the front-end.
See the below service
code:
public function saveThing($elementId, $userId)
{
$this->validateUser($userId);
$this->validateElement($elementId);
// populate the model
// save the record and etc.
}
protected function validateUser($userId)
{
if ($userId == craft()->getUser()->id) {
return true;
}
// return json to the controller?
}
protected function validateElement($elementId)
{
$element = craft()->elements->getElementById($elementId);
if (is_null($element)) {
// return json to the controller?
}
}
So when the conditionals fail on the service, we need to return a response to the controller. Thoughts?