Android端Firebase Auth的getIdToken返回通用异常是否正常?
回答:getIdToken返回通用异常是正常的
先给你吃个定心丸:这种情况是完全正常的,Firebase Auth SDK针对不同操作的异常处理逻辑本来就有差异,getIdToken()刚好是其中一个特殊场景。
为什么会有这种差异?
getIdToken(true)是强制刷新用户令牌的操作,本质上是后台校验当前会话有效性的轻量级请求。Firebase SDK在这个操作的异常处理路径上,并没有像登录(比如signInWithEmailAndPassword)、修改密码这类用户交互操作那样,封装细分的异常子类(比如FirebaseAuthInvalidUserException),而是统一返回通用的FirebaseException,把具体错误码嵌在异常消息里。
怎么正确解析这类错误?
虽然没有特定异常可以直接捕获,但你可以从异常消息里提取错误码来做判断。结合你的现有代码,可以修改parseFirebaseException方法,增加对FirebaseException的处理:
ConnectionFailureReason parseFirebaseException(Exception exception) { try { throw exception; } catch (FirebaseAuthInvalidCredentialsException e) { return ConnectionFailureReason.BAD_CREDENTIALS; } catch (FirebaseAuthInvalidUserException e) { switch (e.getErrorCode()) { case ERROR_USER_NOT_FOUND: return ConnectionFailureReason.BAD_CREDENTIALS; case ERROR_USER_DISABLED: return ConnectionFailureReason.USER_DISABLED; case ERROR_USER_TOKEN_EXPIRED: case ERROR_INVALID_USER_TOKEN: return ConnectionFailureReason.SESSION_EXPIRED; default: return ConnectionFailureReason.SERVER_ERROR; } } catch (FirebaseException e) { // 专门处理getIdToken返回的通用FirebaseException String errorMsg = e.getMessage(); if (errorMsg != null && errorMsg.contains("[")) { // 从消息里提取格式为"[ ERROR_CODE ]"的错误码 int start = errorMsg.indexOf('[') + 1; int end = errorMsg.indexOf(']'); if (start < end) { String errorCode = errorMsg.substring(start, end).trim(); switch (errorCode) { case "USER_DISABLED": return ConnectionFailureReason.USER_DISABLED; case "USER_TOKEN_EXPIRED": case "INVALID_USER_TOKEN": return ConnectionFailureReason.SESSION_EXPIRED; case "USER_NOT_FOUND": return ConnectionFailureReason.BAD_CREDENTIALS; // 根据需要添加其他可能的错误码 default: return ConnectionFailureReason.SERVER_ERROR; } } } return ConnectionFailureReason.UNKNOWN_ERROR; } catch (Exception e) { return ConnectionFailureReason.UNKNOWN_ERROR; } }
额外补充
你提到旧应用里其他Firebase函数会返回特定异常,这完全符合预期——不同操作的异常处理逻辑是SDK内部设计好的。像登录、注册、修改用户信息这类和用户直接交互的操作,SDK会抛出细分的异常子类,方便开发者直接捕获处理;而令牌刷新这种偏底层的会话校验操作,就采用了通用异常+内嵌错误码的方式。
内容的提问来源于stack exchange,提问作者Guillaume
相关产品推荐
相关产品推荐

