遷移至 Java Admin SDK v7

Java 適用的 Firebase Admin SDK 7.0.0 版在 API 中導入了一些重要變更。這個版本的 API 變更主要為 AuthenticationFCM 的錯誤處理功能新增和改善項目。

一般錯誤處理機制的變更

FirebaseException 基礎類別現在會公開幾個新的屬性:

  • ErrorCode getErrorCode():傳回與例外狀況相關聯的平台錯誤代碼。每個 FirebaseException 例項都保證會具有非空值的平台錯誤代碼。可能的平台錯誤代碼定義為新的列舉型別 ErrorCode
  • IncomingHttpResponse getHttpResponse():傳回與例外狀況相關聯的 HTTP 回應。如果例外狀況是由非後端 HTTP 回應所造成,則可能為空值。

如前所述,SDK 中定義的其他例外狀況類型 (例如 FirebaseAuthExceptionFirebaseMessagingException) 大多是從 FirebaseException 基礎類別衍生而來。

驗證錯誤處理機制變更

FirebaseAuth 類別中的所有 API 都可能擲回 FirebaseAuthException 例項。非同步 API (例如傳回 ApiFuture 的方法) 可能會在包裝 FirebaseAuthExceptionExecutionException 中失敗。在新的列舉型別 AuthErrorCode 中,公開定義了 Auth 專屬的錯誤代碼。

舊版 (<= 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");
  }
}

現已支援 (7.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 的方法) 可能會在包裝 FirebaseMessagingExceptionExecutionException 中失敗。Authentication 專屬錯誤代碼已在新的列舉類型 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");
  }
}

現已支援 (7.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 以外的項目。您可以實作錯誤處理邏輯,視需要檢查這兩個錯誤代碼。

Authentication 自訂版權聲明

已淘汰的 FirebaseAuth.setCustomClaims() 方法已移除。請改用 FirebaseAuth.setCustomUserClaims()

舊版 (<= v6.15.0)

FirebaseAuth.getInstance().setCustomClaims(uid, claims);

現已支援 (7.0.0 以上版本)

FirebaseAuth.getInstance().setCustomUserClaims(uid, claims);

FCM 通知建構函式

已移除 Notification 類別的已淘汰建構函式。使用 Notification.Builder 類別建立新的例項。

舊版 (<= v6.15.0)

Notification notification = new Notification(title, body, url);

現已支援 (7.0.0 以上版本)

Notification notification = Notification.builder()
  .setTitle(title)
  .setBody(body)
  .setImage(url)
  .build();