遷移至 Java Admin SDK v7

Java 專用 Firebase Admin SDK 7.0.0 版對 API 進行了一些重要變更。這個版本中的 API 變更主要是新增和改善 Authentication 和 FCM 的錯誤處理機制。

一般錯誤處理異動

FirebaseException 基礎類別現在會顯示幾項新屬性:

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

和之前一樣,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。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");
  }
}

目前 (>= 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");
  }
}

除了從基本 FirebaseException 類型繼承的 ErrorCode 之外,還有 MessagingErrorCode。您可以實作錯誤處理邏輯,視需要檢查這兩種錯誤代碼。

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();