Try catch block doesn't catch rethrown error - flutter

UI code:
try {
authService.signInWithEmailAndPassword(
emailController.text, passwordController.text);
} catch (error) {
print("ui rethrow");
}
Auth service code:
Future<User?> signInWithEmailAndPassword(
String email,
String password,) async {
try {
final credential = await _firebaseAuth.signInWithEmailAndPassword(
email: email, password: password);
return _userFromFirebase(credential.user);
} catch (e) {
print("service throw");
rethrow;
}
}
I want to rethrow FirebaseAuthException from the authentication service to the UI, so I can give a user prompt with what went wrong, but the UI try-catch block doesn't catch the rethrown error.
Why doesn't my code work?

Related

Cant register FireBase user from Flutter

I am unable to register an user from my app written in Flutter. I am also unable to get some form for error message. I can debug and see my createUser function is called and the arguments looks good. Nothing happens after I call "FirebaseAuth.instance.createUserWithEmailAndPassword". No exception and nothing is printed in the FireBase emulator console. What am I missing here? Here is what I got:
Emulator:
Running on 127.0.0.1:9099
main.dart:
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp(options: DefaultFirebaseOptions.currentPlatform,);
try {
await FirebaseAuth.instance.useAuthEmulator('localhost', 9099);
} catch (e) {
// ignore: avoid_print
print(e);
}
runApp(
MaterialApp(
title: "Foo",
home: buildContent(),
),
);
}
Registration function:
void createUser() async {
print("createUser()");
try {
final credential = await FirebaseAuth.instance.createUserWithEmailAndPassword(
email: nameController.text,
password: passwordController.text,
);
//final credential = await FirebaseAuth.instance.createUserWithEmailAndPassword(email: nameController.text, password: passwordController.text);
} on FirebaseAuthException catch (e) {
if (e.code == 'weak-password') {
print('The password provided is too weak.');
} else if (e.code == 'email-already-in-use') {
print('The account already exists for that email.');
}
} catch (e) {
print(e);
}
}
Edit:
I keep getting this message when i call "createUserWithEmailAndPassword"
W/System (26859): Ignoring header X-Firebase-Locale because its value was null.
In your createUser() Function i think you're sending empty values to firebase
request parameters like this and try it again
void createUser(String name, String Password) async {
print("createUser()");
try {
final credential = await FirebaseAuth.instance.createUserWithEmailAndPassword(
email: name,
password: password,
);
print("User Created Success);
//final credential = await FirebaseAuth.instance.createUserWithEmailAndPassword(email: nameController.text, password: passwordController.text);
} on FirebaseAuthException catch (e) {
if (e.code == 'weak-password') {
print('The password provided is too weak.');
} else if (e.code == 'email-already-in-use') {
print('The account already exists for that email.');
}
} catch (e) {
print(e);
}
}
So after some trail and error I ended up adding:
android:usesCleartextTraffic="true"
To the manifest file:
...\my_project\android\app\src\main\AndroidManifest.xml
I am not sure I like the "fix" as I think the requests are sent unencrypted. A google search gives me this description:
Android 6.0 introduced the useCleartextTraffic attribute under application element in android manifest. The default value in Android P is “false”. Setting this to true indicates that the app intends to use clear network traffic

Catch block not called in async future flutter

Why is my catch block not called in this code when there is exception
Future registerWithCredentials() async {
if(state.status == RegisterStatus.loading) return;
emit(state.copyWith(status: RegisterStatus.loading));
try{
await _authRepository.register(email: state.email, password: state.password);
emit(state.copyWith(status: RegisterStatus.success));
}catch (e) {
//catch errors
debugPrint('except: "there is an error"');
emit(state.copyWith(status: RegisterStatus.error));
}
}
I have also tried like this:
try {
await _authRepository.register(email: state.email, password: state.password);
emit(state.copyWith(status: RegisterStatus.success));
} on FirebaseAuthException catch (e) {
debugPrint('except: "there is an error"');
emit(state.copyWith(status: RegisterStatus.error));
}
Repository -> register
Future<void> register({
required String email,
required String password,
}) async {
try {
await _firebaseAuth.createUserWithEmailAndPassword(email: email,
password: password);
} catch(_) {
//the catch here works but I need to send the error to cubit above and
also send to UI... how to do that
}
}
This what I want to do -> Send the error from repository to cubit to ui and display in widget/ui
If you catch the exception in the repository, then you have "used" (handled) the exception. If you want to catch the same exception in the bloc, you'll have to rethrow it. So, either re-throw the exception, or remove the try catch in the repository.

Is there any error in the try-catch exception handling below?

I tried to handle an exception while a user is trying to login after being authenticated by firebase. But this try-catch is not working in my flutter project.
Can someone let me know where did i go wrong? I have attached my code below.
Thank you in advance.
class AuthService {
//Creating an instance of firebase.
final auth.FirebaseAuth _firebaseAuth = auth.FirebaseAuth.instance;
User? _userFromFirebase(auth.User? user) {
if (user == null) {
return null;
}
return User(user.uid, user.email);
}
Stream<User?>? get user {
return _firebaseAuth.authStateChanges().map(_userFromFirebase);
}
Future<User?> signInWithEmailAndPassword(
String email,
String password,
) async {
try {
final credential = await _firebaseAuth.signInWithEmailAndPassword(
email: email, password: password);
return _userFromFirebase(credential.user);
} on Exception catch (_, e) {
//I want to display a toast message if the login fails here.
print(e);
}
}
Future<void> signOut() async {
return await _firebaseAuth.signOut();
}
}
In your try-catch block you are catching Exception types, but Firebase Authentication has its own exception type, FirebaseAuthException.
For possible error codes for this specific sign-in see here, but there are others as well.
Check the following code:
try {
final credential = await _firebaseAuth.signInWithEmailAndPassword(
email: email, password: password);
return _userFromFirebase(credential.user);
} on FirebaseAuthException catch (e) {
// here you will have the different error codes in `e.code`
// for example `invalid-email` or `wrong-password`
}
It is up to you how do you handle these errors. You can return the error code for example and handle it from where you call this function (as h8moss suggested in comment).
And keep in mind that there are other possible reasons for a sign-in to fail than FirebaseAuthException. For example network connection can be down. So a more complete solution to catch other errors as well would be something like:
try {
// sign in
} on FirebaseAuthException catch (e) {
// handle Firebase Authentication exceptions
} catch (e) {
// handle other exceptions
}

Firebase, how do I catch a exception and tell the user about it? [duplicate]

This question already has answers here:
How to Handle Firebase Auth exceptions on flutter
(18 answers)
Closed 1 year ago.
Future<Users?>createUserWithEmailAndPassword(String email, String password) async {
final credential = await _firebaseAuth.createUserWithEmailAndPassword(
email: email,
password: password
);
return _userFromFirebase(credential.user);
}
You can catch the exception with a try/catch and show it on the UI in a number of ways. Example
Future<Users?> createUserWithEmailAndPassword(
String email,
String password,
) async {
try {
final credential = await _firebaseAuth.createUserWithEmailAndPassword(
email: email,
password: password,
);
return _userFromFirebase(credential.user);
} on FirebaseException catch (e) {
// FirebaseException
print(e.message);
} catch (e) {
// all other exceptions
print(e);
}
}

Flutter error catch e.message not working

void createUser(String email, String password) async {
try {
await _auth
.createUserWithEmailAndPassword(email: email, password: password)
.then((value) => Get.offAll(Home()));
} catch (e) {
Get.snackbar("Error while creating account", e.message, //Error on e.message
snackPosition: SnackPosition.BOTTOM);
}
}
Error: The getter 'message' isn't defined for the class 'Object'. Try
correcting the name to the name of an existing getter, or defining a
getter or field named 'message'.
Any idea why it is not working?
The reason for this is the e object you are catching doesnt have the message property. You can see which type it is by using print(e.runtimeType). If you want to catch some specific type of Exception, you should try:
try {
//
} on SomeClass catch (e) {
print(e.message)
} catch (e) {
//
}
Problem solved by adding on FirebaseAuthException before catch and converting e.message to e.message.tostring()
void createUser(String email, String password) async {
try {
await _auth
.createUserWithEmailAndPassword(email: email, password: password)
.then((value) => Get.offAll(Home()));
} on FirebaseAuthException catch (e) {
Get.snackbar("Error while creating account", e.message.toString(),
snackPosition: SnackPosition.BOTTOM);
}
}
Problem solved by adding on FirebaseAuthException before catch and converting e.message to e.message.tostring().