This will not work because the method you are calling is asynchronous. This exception would be thrown to another thread, where the network call is taking place, and it wouldn’t work anyway. This DAO pattern you’re trying to do simply doesn’t work in asynchronous paradigms without changes.
You have not specified the programming language or execution environment, but if it is an environment in which there is no problem in locking the thread current while waiting for the result, you can use Tasks.await
to make your code wait until the completion of the Task
resulting from createUserWithEmailAndPassword
. Example:
public void createAuth(User user) throws FirebaseAuthWeakPasswordException {
Task<AuthResult> createUserAccountTask = mFirebaseAuth.createUserWithEmailAndPassword(user.getEmail(), user.getPassword());
try {
// Nessa linha, a execução da thread atual vai congelar até a tarefa concluir (com sucesso ou erro)
Tasks.await(createUserAccountTask);
if (createUserAccountTask.isSuccessful()) {
//Fazer algo caso a criação do usuário tenha ocorrido com sucesso.
} else {
Exception e = createUserAccountTask.getException();
if (e.getClass().equals(FirebaseAuthWeakPasswordException.class)) {
throw new FirebaseAuthWeakPasswordException(e.getCause().toString(), e.getLocalizedMessage().toString(), e.getMessage().toString());
} else if (e.getClass().equals(FirebaseAuthUserCollisionException.class)) {
throw new FirebaseAuthUserCollisionException(this.e.getCause().toString(), this.e.getLocalizedMessage().toString());
}
}
} catch (ExecutionException e) {
// faça alguma coisa aqui em caso de ExecutionException
} catch (InterruptedException e) {
// faça alguma coisa aqui caso a tarefa seja interrompida no meio
}
}
However, be aware that this can freeze the user screen if you run on thread leading.
A common and simple approach to implement when it is not possible to block the current thread execution is to use so-called callbacks or listeners. You must require that those who call your function pass to it, in addition to the user and password, objects that explain what to do when the task is completed. For example, you can define these interfaces:
@FunctionalInterface
interface UserCreationSuccessfulListener {
void onUserCreated();
}
@FunctionalInterface
interface UserCreationFailedListener {
void onFailedToCreateUser(Exception e);
}
And then you can change your function to be like this:
public void createAuth(User user, final UserCreationSuccessfulListener successListener, final UserCreationFailedListener failureListener) throws FirebaseAuthWeakPasswordException {
mFirebaseAuth.createUserWithEmailAndPassword(user.getEmail(), user.getPassword())
.addOnSuccessListener(new OnSuccessListener<AuthResult>() {
@Override
public void onSuccess(AuthResult authResult) {
successListener.onUserCreated();
}
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
if (e.getClass().equals(FirebaseAuthWeakPasswordException.class)) {
failureListener.onFailedToCreateUser(
new FirebaseAuthWeakPasswordException(e.getCause().toString(), e.getLocalizedMessage(), e.getMessage())
);
} else if (e.getClass().equals(FirebaseAuthUserCollisionException.class)) {
failureListener.onFailedToCreateUser(new FirebaseAuthUserCollisionException(e.getCause().toString(), e.getLocalizedMessage()));
} else {
failureListener.onFailedToCreateUser(e);
}
}
}
);
}
And use it like this:
createAuth(user, new UserCreationSuccessfulListener() {
@Override
public void onUserCreated() {
// fazer algo aqui em caso de sucesso
}
}, new UserCreationFailedListener() {
@Override
public void onFailedToCreateUser(Exception e) {
// fazer algo aqui em caso de erro
}
});
Or better yet:
createAuth(user, () -> {
// fazer algo aqui em caso de sucesso
}, (error) -> {
// fazer algo aqui em caso de erro
});
There are other options. You can, for example, return the Task that the createUserWithEmailAndPassword
and let the client code of your function turn with the result. One problem is that it creates a client code dependency with the Google Play Services API.
Enter the code that is causing the problem, the error message, and use the tags to indicate which programming language/platform you are using.
– Pablo Almeida