適用於 Java 的 Firebase Admin SDK 版本 7.0.0 在 API 中引入了一些重要變更。主要是,此版本中的 API 變更是身份驗證和 FCM 錯誤處理的新增和改進。
一般錯誤處理更改
FirebaseException
基底類別現在公開了幾個新屬性:
-
ErrorCode getErrorCode()
:傳回與異常相關的平台錯誤碼。FirebaseException
的每個實例都保證具有非空平台錯誤代碼。可能的平台錯誤代碼被定義為新的枚舉類型ErrorCode
。 -
IncomingHttpResponse getHttpResponse()
:傳回與異常相關的 HTTP 回應。如果異常是由後端 HTTP 回應以外的原因引起的,則可能為 null。
與先前一樣,SDK 中定義的大多數其他異常類型(例如FirebaseAuthException
、 FirebaseMessagingException
)均衍生自FirebaseException
基底類別。
身份驗證錯誤處理更改
FirebaseAuth
類別中的所有 API 都可能會拋出FirebaseAuthException
實例。非同步 API(例如,傳回ApiFuture
方法)可能會失敗,並出現包裝FirebaseAuthException
ExecutionException
。 Auth 特定的錯誤代碼在新的枚舉類型AuthErrorCode
中公開定義。
之前 (<= v6.15.0)
try {
FirebaseAuth.getInstance().verifyIdToken(idToken, true);
} catch (FirebaseAuthException ex) {
if (ex.getErrorCode().equals("id-token-revoked")) {
System.err.println("ID token has been revoked");
} else {
System.err.println("ID token is invalid");
}
}
現在(>= v7.0.0)
try {
FirebaseAuth.getInstance().verifyIdToken(idToken, true);
} catch (FirebaseAuthException ex) {
if (ex.getAuthErrorCode() == AuthErrorCode.REVOKED_ID_TOKEN) {
System.err.println("ID token has been revoked");
} else {
System.err.println("ID token is invalid");
}
}
AuthErrorCode
是從基本FirebaseException
類型繼承的ErrorCode
的補充。如果需要,您可以實作檢查兩個錯誤代碼的錯誤處理邏輯。
FCM 錯誤處理更改
FirebaseMessaging
類別中的所有 API 都可能會拋出FirebaseMessagingException
的實例。非同步 API(例如,傳回ApiFuture
方法)可能會失敗,並出現包裝FirebaseMessagingException
ExecutionException
。特定於身份驗證的錯誤代碼在新枚舉類型MessagingErrorCode
中公開定義。
之前 (<= v6.15.0)
try {
FirebaseMessaging.getInstance().send(message);
} catch (FirebaseMessagingException ex) {
if (ex.getErrorCode().equals("registration-token-not-registered")) {
System.err.println("Device token has been unregistered");
} else {
System.err.println("Failed to send the notification");
}
}
現在(>= v7.0.0)
try {
FirebaseMessaging.getInstance().send(message);
} catch (FirebaseMessagingException ex) {
if (ex.getMessagingErrorCode() == MessagingErrorCode.UNREGISTERED) {
System.err.println("Device token has been unregistered");
} else {
System.err.println("Failed to send the notification");
}
}
MessagingErrorCode
是從基本FirebaseException
類型繼承的ErrorCode
的補充。如果需要,您可以實作檢查兩個錯誤代碼的錯誤處理邏輯。
身份驗證自訂聲明
已棄用的FirebaseAuth.setCustomClaims()
方法已被刪除。請改用FirebaseAuth.setCustomUserClaims()
。
之前 (<= v6.15.0)
FirebaseAuth.getInstance().setCustomClaims(uid, claims);
現在(>= v7.0.0)
FirebaseAuth.getInstance().setCustomUserClaims(uid, claims);
FCM 通知建構函數
Notification
類別已棄用的建構函式已被刪除。使用Notification.Builder
類別建立新實例。
之前 (<= v6.15.0)
Notification notification = new Notification(title, body, url);
現在(>= v7.0.0)
Notification notification = Notification.builder()
.setTitle(title)
.setBody(body)
.setImage(url)
.build();