Browse Source

添加获取当前用户名的方法,自捕获异常 返回预定异常值

NorthLan 6 years ago
parent
commit
c4176a7dc0
1 changed files with 35 additions and 5 deletions
  1. 35 5
      zen-api/src/main/kotlin/com/gxzc/zen/umps/util/SSOUtil.kt

+ 35 - 5
zen-api/src/main/kotlin/com/gxzc/zen/umps/util/SSOUtil.kt

@@ -9,6 +9,7 @@ import com.gxzc.zen.umps.common.ZenPermission
 import com.gxzc.zen.umps.constant.ZenHttpSession
 import org.apache.shiro.SecurityUtils
 import org.apache.shiro.session.Session
+import org.slf4j.LoggerFactory
 
 /**
  * SSO 工具类
@@ -19,6 +20,8 @@ import org.apache.shiro.session.Session
 @Suppress("UNCHECKED_CAST")
 object SSOUtil {
     private var permissionService: IPermissionService? = SpringContextHolder.getBean(IPermissionService::class.java)
+    private val logger = LoggerFactory.getLogger(SSOUtil::class.java)
+    private const val NA = "NA"
 
     fun getSession(): Session? {
         return SecurityUtils.getSubject().getSession(false)
@@ -35,22 +38,49 @@ object SSOUtil {
     /**
      * 获取当前登陆 账号
      */
-    fun getCurAccount(): String? {
-        return SecurityUtils.getSubject().principal?.toString()
+    fun getCurAccount(): String {
+        return try {
+            SecurityUtils.getSubject().principal.toString()
+        } catch (e: Throwable) {
+            logger.warn("get curAccount error, return empty string:\"\"")
+            ""
+        }
     }
 
     /**
      * 获取当前登陆 userId
      */
-    fun getCurUserId(): Long? {
-        return getSession()?.getAttribute(ZenHttpSession.SESSION_KEY_USER_ID) as? Long
+    fun getCurUserId(): Long {
+        return try {
+            getSession()?.getAttribute(ZenHttpSession.SESSION_KEY_USER_ID) as Long
+        } catch (e: Throwable) {
+            logger.warn("getCurUserId error, return -1")
+            -1
+        }
     }
 
     /**
      * 获取当前登陆 基本信息
      */
     fun getCurUserInfo(): SysUser? {
-        return getSession()?.getAttribute(ZenHttpSession.SESSION_KEY_USER_INFO) as? SysUser
+        return try {
+            getSession()?.getAttribute(ZenHttpSession.SESSION_KEY_USER_INFO) as? SysUser
+        } catch (e: Throwable) {
+            logger.warn("get curUserInfo error, return null")
+            null
+        }
+    }
+
+    /**
+     * 获取当前登陆用户名
+     */
+    fun getCurUserName(): String {
+        return try {
+            getCurUserInfo()?.username!!
+        } catch (e: Throwable) {
+            logger.warn("getCurUserName error, return given NA: \"NA\" ")
+            ""
+        }
     }
 
     /**