如果用户在数据库中没有任何角色,则检查用户角色时 JAVA 出错

Error in JAVA when checking a user roles if the user does not have any roles in DB

我正在处理以查看当前用户是否具有特定角色。问题是用户有一个角色(即使它不是我正在检查的角色)一切正常。但是,如果用户没有角色,则对用户角色的检查会抛出 NUllPointerException。代码是:

Database appDB = this.getAppDB();
if (appDB == null) {
    if (debug) System.out.println("App DB is Null " );
}else{
    if (debug) System.out.println("App DB is Not Null " );
}
try{
    if (debug) System.out.println("WFS*** get roles");
    roles = appDB.getACL().getEntry(fullUser).getRoles();
    if (debug) System.out.println("Got User Roles  " );
}catch(NotesException e){
    roles.clear();
    if (debug) System.out.println("User Roles Null " ); 
}

日志中显示的消息 "WFS*** get roles" 变量 fullUser 是正确的,因为它在用户在 appDB 中具有角色时有效。 不确定为什么 catch 没有捕获错误,以及为什么会出现错误而不只是返回一个空向量。

试试 database.queryAccessRoles(userName) - 无论用户是否有任何角色或(这可能是这里的问题)ACL 中的命名条目,这都应该有效。

Not sure why the catch is not trapping the error...

因为您在 catch 块中对空对象调用了 clear()。如果 roles 对象赋值失败,它仍然是 null,你不能调用它的方法。

几点改进建议:

  • 始终使用 var 作为变量
  • 不要吞下异常
  • 不要进行级联调用(尤其是当出现问题时)

我打赌当你调用

时你的 NullPointerException 发生了
roles.clear();

这意味着当您尝试查询用户的角色时抛出异常。

尝试做:

if(roles!=null){
    roles.clear();
}

希望对您有所帮助!