2

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?

4

There are several ways you could go about this.

One that I tend to prefer is to go ahead and have your controller grab whatever data it needs from POST and populate a Model with it.

That model is what gets passed into your service layer. Your service layer can run validation on the model (if any validation fails, you can retrieve the errors with $model->getErrors().

You can perform any additional custom logic and if any of that fails, use $model->addError() and return false.

Since the model will have been passed in by reference, your controller can see that false was returned and call $model->getErrors(), format those however you need and use $this->returnJson($myErrors) to send the errors back to the browser as JSON.

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.