beforeDelete return false

Hi There guys,

I am developing a REST Api with the possibility for users to add and delete comments: about the deletion I want that only the owner of the comment can delete its comment so I have overridden the beforeDelete() method inside the Comment ActiveRecord Class in this way:




...

public function beforeDelete() {

    if(!parent::beforeDelete()){

      return false;

    }

    $userApi = AuthHelper::getUserByToken();

    if(!is_object($userApi)){

      $this->addError('id_user', 'Unrecognized user');

      return false;

    }

    if($this->id_user != $userApi->id){

      $this->addError('id_user', 'Not authorized to perform this action');

      return false;

    }

    return true;

  }

...



The static method AuthHelper::getUserByToken() basically just get the token from the request header, and invoke the User::findIdentityByAccessToken to return the user object (if exist).




...

public static function getUserByToken() {

    $headers = \Yii::$app->request->headers;

    $token_value = $headers->get('Authorization');

    $token = str_replace('Bearer ', '', $token_value);

    return User::findIdentityByAccessToken($token);

  }

...



However if I try to delete a comment that does not belong to me, the server deny my request but do not show any of the errors I declared using the addError() method, but instead it send me a 500 Server Error:




{

    "name": "Internal Server Error",

    "message": "Failed to delete the object for unknown reason.",

    "code": 0,

    "status": 500,

    "type": "yii\\web\\ServerErrorHttpException"

}



My question is: is it a normal behavior to throw a ServerErrorHttpException because the beforeDelete() return false or it might be related to other things? Could it be any better way to deny the deletion and send back a proper error message instead of a generic 500 ServerError?

Thank you in advance

Raffaele

Yes, see the implementation of DeleteAction:




if ($model->delete() === false) {

            throw new ServerErrorHttpException('Failed to delete the object for unknown reason.');

        }



http://www.yiiframework.com/doc-2.0/guide-rest-error-handling.html

Thank you very much Partik for your answer, at the end of the day I have solved throwing a 401 UnauthorizedHttpException, is not that elegant but it works!




if($this->id_user != $userApi->id){

   throw new \yii\web\UnauthorizedHttpException('Not authorized to perform this action');

}