遷移至 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 中公開定義。

變更前 (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 的方法) 可能會失敗,並傳回包裝 FirebaseMessagingExceptionExecutionExceptionAuthentication 專屬錯誤代碼已在新列舉型別 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 以外的屬性。您可以實作錯誤處理邏輯,視需要檢查這兩種錯誤代碼。

Authentication 自訂聲明

已移除淘汰的 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();