Search code examples
yii2rbac

Handle runtime exception in yii2 in rbac


How can I handle rbac exceptions in yii2. The below function generating an exception while assigning the user a role.

  $r = new DbManager;
  $r->init();
  $role = (object) array('name' => $roleName);

if ( $r->assign($role, $userId) ) {

The above $r->assign generates the exception, such as "Integrity constraint violation". I want to handle all these exceptions. I tried try catch block but no success?

Here is my full code:-

$roleName = $this->__checkIfRoleIsValid(\yii::$app->request->post());
        $msg = "The role cannot be changed.";
        $statusCode = 500;
        $success = false;

        if ( !empty($roleName) ) {
            $userId = $this->_getUserId();
            if ( empty($userId) ) {
                \yii::$app->response->statusCode = 500;
                return ['success' => false, 'message' => 'Unauthorize: Invalid x-user-authtoken provided.'];
                \Yii::$app->end();   
            }
            $r = new DbManager;
            $r->init();
            $role = (object) array('name' => $roleName);

            if ( $r->assign($role, $userId) ) {
                $statusCode = 204;
                $msg = "";
                $success = true;
            } 
        }

        \yii::$app->response->statusCode = $statusCode;
        return ['success' => $success, 'message' => $msg];
        \yii::$app->end(); 

Solution

  • You need to use yii\db\Exception in catch.

    Try this code.

    try {
    
         $r->assign($role, $userId);
         $statusCode = 204;
         $msg = "";
         $success = true;
    } catch(yii\db\Exception $e) {
          \Yii::$app->session->setFlash('warning', 'Your message.');
          $success = false;
    }