在rbac中处理yii2中的运行时异常

时间:2015-10-19 10:51:23

标签: yii2 rbac

如何在yii2中处理rbac异常。 以下函数在为用户分配角色时生成异常。

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

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

上述$r->assign会生成异常,例如"完整性约束违规"。我想处理所有这些异常。我尝试过试试catch但没有成功?

这是我的完整代码: -

$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(); 

1 个答案:

答案 0 :(得分:-1)

您需要在yii\db\Exception中使用catch

试试这段代码。

try {

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