迁移到 Java Admin SDK v7

Java 版 Firebase Admin SDK 7.0.0 版本在 API 中引入了一些重要更改。主要来讲,此版本中的 API 更改对 Authentication 和 FCM 的错误处理进行了补充和改进。

常规错误处理更改

FirebaseException 基类现在公开了几个新属性:

  • ErrorCode getErrorCode():返回与异常关联的平台错误代码。FirebaseException 的每个实例都保证有一个非 null 平台错误代码。可能的平台错误代码被定义为新的枚举类型 ErrorCode
  • IncomingHttpResponse getHttpResponse():返回与异常关联的 HTTP 响应。如果异常不是由后端 HTTP 响应引起的,则可能为 null。

与以前一样,SDK 中定义的大多数其他异常类型(例如 FirebaseAuthExceptionFirebaseMessagingException)都派生自 FirebaseException 基类。

Auth 错误处理更改

FirebaseAuth 类中的所有 API 都可能会抛出 FirebaseAuthException 实例。异步 API(例如,返回 ApiFuture 的方法)可能会失败,并抛出封装了 FirebaseAuthExceptionExecutionException。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 的方法)可能会失败,并抛出封装了 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");
  }
}

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