Gestione degli errori

Gli SDK di autenticazione Firebase forniscono un modo semplice per individuare i vari errori che possono verificarsi utilizzando i metodi di autenticazione. Gli SDK per Flutter espongono questi errori tramite la classe FirebaseAuthException .

Come minimo vengono forniti un code e message , tuttavia in alcuni casi vengono fornite anche proprietà aggiuntive come un indirizzo e-mail e credenziali. Ad esempio, se l'utente sta tentando di accedere con un indirizzo email e una password, eventuali errori generati possono essere rilevati esplicitamente:

try {
  await FirebaseAuth.instance.signInWithEmailAndPassword(
    email: "barry.allen@example.com",
    password: "SuperSecretPassword!"
  );
} on FirebaseAuthException catch  (e) {
  print('Failed with error code: ${e.code}');
  print(e.message);
}

Ciascun metodo fornisce vari codici di errore e messaggi a seconda del tipo di chiamata di autenticazione. L' API di riferimento fornisce dettagli aggiornati sugli errori per ciascun metodo.

Altri errori come too-many-requests o operation-not-allowed potrebbero essere generati se raggiungi la quota di autenticazione Firebase o non hai abilitato un provider di autenticazione specifico.

Gestione degli errori account-exists-with-different-credential

Se hai abilitato l'impostazione Un account per indirizzo email nella console Firebase , quando un utente tenta di accedere a un provider (come Google) con un indirizzo email già esistente per il provider di un altro utente Firebase (come Facebook), viene visualizzato l'errore auth/account-exists-with-different-credential viene generato insieme a una classe AuthCredential (token ID Google). Per completare il flusso di accesso al fornitore desiderato, l'utente deve prima accedere al fornitore esistente (ad esempio Facebook) e quindi collegarsi al precedente AuthCredential (token ID di Google).

FirebaseAuth auth = FirebaseAuth.instance;

// Create a credential from a Google Sign-in Request
var googleAuthCredential = GoogleAuthProvider.credential(accessToken: 'xxxx');

try {
  // Attempt to sign in the user in with Google
  await auth.signInWithCredential(googleAuthCredential);
} on FirebaseAuthException catch (e) {
  if (e.code == 'account-exists-with-different-credential') {
    // The account already exists with a different credential
    String email = e.email;
    AuthCredential pendingCredential = e.credential;

    // Fetch a list of what sign-in methods exist for the conflicting user
    List<String> userSignInMethods = await auth.fetchSignInMethodsForEmail(email);

    // If the user has several sign-in methods,
    // the first method in the list will be the "recommended" method to use.
    if (userSignInMethods.first == 'password') {
      // Prompt the user to enter their password
      String password = '...';

      // Sign the user in to their account with the password
      UserCredential userCredential = await auth.signInWithEmailAndPassword(
        email: email,
        password: password,
      );

      // Link the pending credential with the existing account
      await userCredential.user.linkWithCredential(pendingCredential);

      // Success! Go back to your application flow
      return goToApplication();
    }

    // Since other providers are now external, you must now sign the user in with another
    // auth provider, such as Facebook.
    if (userSignInMethods.first == 'facebook.com') {
      // Create a new Facebook credential
      String accessToken = await triggerFacebookAuthentication();
      var facebookAuthCredential = FacebookAuthProvider.credential(accessToken);

      // Sign the user in with the credential
      UserCredential userCredential = await auth.signInWithCredential(facebookAuthCredential);

      // Link the pending credential with the existing account
      await userCredential.user.linkWithCredential(pendingCredential);

      // Success! Go back to your application flow
      return goToApplication();
    }

    // Handle other OAuth providers...
  }
}