Flutter error catch e.message not working - flutter

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().

Related

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
}

Try catch block doesn't catch rethrown error

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?

A value of type 'Stream<User?>' can't be returned from the function 'user' because it has a return type of 'Stream<User>?'

I am getting red line on auth.authStateChanges(),
Error says : A value of type 'Stream<User?>' can't be returned from the function 'user' because it has a return type of 'Stream?'.
class Auth {
final FirebaseAuth auth;
Auth({required this.auth});
Stream<User>? get user => auth.authStateChanges(); <-- here
Update now i get this error:
Future<String?> createAccount({required String email, required String password}) async {
try {
await auth.createUserWithEmailAndPassword( <-- here **auth**
email: email.trim(),
password: password.trim(),
);
return "Success";
} on FirebaseAuthException catch (e) {
return e.message;
} catch (e) {
rethrow;
}
}
Here is your updated class
import 'package:firebase_auth/firebase_auth.dart';
class Auth {
final FirebaseAuth auth;
Auth({required this.auth});
Stream<User?> get user => auth.authStateChanges();
Future<String?> createAccount({required String email, required String password}) async {
try {
await FirebaseAuth.instance.createUserWithEmailAndPassword(
email: email.trim(),
password: password.trim(),
);
return "Success";
} on FirebaseAuthException catch (e) {
return e.message;
} catch (e) {
rethrow;
}
}
}

Flutter FirebaseAuth: SignInWithEmailAndPassword unable to handle error when the email address is badly formatted

Here is my email sign in method in my FirebaseAuthService class:
#override
Future<UserCustom> signInWithEmail(
String emailAddress, String password) async {
try {
UserCredential _signInWithEmailAndPasswordGoogle = await _auth
.signInWithEmailAndPassword(email: emailAddress, password: password);
if (_signInWithEmailAndPasswordGoogle.user != null) {
return _userToUserModel(_signInWithEmailAndPasswordGoogle.user);
} else {
throw PlatformException(
code: 'SIGN_IN_INTERRUPTED', message: 'Sin in interrupted');
}
} on PlatformException {
print('Happened');
rethrow;
}
}
And here is where the exception should be handled:
// creating the submit function
Future<void> _submit(EmailSignInModelProviderPattern model) async {
// if it is on sign in use sign in function ELSE use register function
try {
await model.submit();
Navigator.pop(context);
} on PlatformException catch (e) {
CustomErrorPlatformException(
title: 'Sign in failed',
exception: e,
).show(context);
} catch(e){
print(e.toString());
}
}
And yet when I enter a badly formatted address the process is interrupted at message_codecs.dart file at the method dynamic decodeEnvelope(ByteData envelope){... line 572 with error message:
Exception has occurred. PlatformException
(PlatformException(firebase_auth,
com.google.firebase.auth.FirebaseAuthInvalidCredentialsException: The
email address is badly formatted., {code: invalid-email,
additionalData: {}, message: The email address is badly formatted.}))
I couldn't figure out how to handle this exception, knowing that it never happened to me before upgrading to firebase_auth: ^0.18.0+1.
check this issues where it explains why is happens
https://github.com/FirebaseExtended/flutterfire/issues/1760
.
If you use an Emulator and change textfield with tab button then there's an extra space left behind on that email field ->*myemail#gmail.com *
to avoid this extra space you have to use .trim() method.
in your case
UserCredential _signInWithEmailAndPasswordGoogle = await _auth
.signInWithEmailAndPassword(email: emailAddress.trim(), password: password);
I guess this solves your problem.
I was having a similar issue, your code looks fine. Try disabling Uncaught Expectations in the Debugging panel for VScode solved the issue for me.
https://github.com/FirebaseExtended/flutterfire/issues/3303#issuecomment-687560133