如何在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();
答案 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;
}