Gestione degli errori

Gli SDK Firebase Authentication offrono un modo semplice per individuare i vari errori che potrebbero verificarsi utilizzando i metodi di autenticazione. Gli SDK per Flutter mostrano questi errori tramite la classe FirebaseAuthException.

Sono forniti almeno un code e un message, ma in alcuni casi vengono fornite anche proprietà aggiuntive come un indirizzo email e le credenziali. Ad esempio, se l'utente sta tentando di accedere con un indirizzo email e una password, gli 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);
}

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

Potrebbero essere visualizzati altri errori, come too-many-requests o operation-not-allowed, se raggiungi la quota di Firebase Authentication o non hai abilitato un provider di autenticazione specifico.

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

Se hai attivato l'impostazione Un account per indirizzo email nella console di Firebase, quando un utente tenta di accedere a un provider (ad esempio Google) con un indirizzo email già esistente per il provider di un altro utente Firebase (ad esempio Facebook), viene generato l'errore auth/account-exists-with-different-credential insieme a una classe AuthCredential (token ID Google). Per completare il flusso di accesso al provider previsto, l'utente deve prima accedere al provider esistente (ad es. Facebook) e poi eseguire il collegamento all'altroAuthCredential (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...
 
}
}