Home > other >  Error catch... The argument type 'Object' can't be assigned t
Error catch... The argument type 'Object' can't be assigned t

Time:02-08

I"m tring to catch standard exception with the following code:

 @override
  Stream<LoginState> mapEventToState(LoginEvent event) async* {
    if (event is LoginUsernameChanged) {
      yield state.copyWith(username: event.username);
    } else if (event is LoginPasswordChanged) {
      yield state.copyWith(password: event.password);
    } else if (event is Loginsubmitted) {
      yield state.copyWith(formStatus: state.formStatus);
      try {
        await authRepo.login();
        yield state.copyWith(formStatus: SubmissionSuccess());
        
      } catch (e) {
        yield state.copyWith(formStatus:  SubmissionFailed(e));
      }
    }
  }

The SubmissionFailed class code is :

class SubmissionFailed extends FromSubmissionStatus {
  final Exception exception;
  **SubmissionFailed(this.exception);**
}

How ever the compiler say:

The argument type 'Object' can't be assigned to the parameter type 'Exception'.

Why? Thank you !

CodePudding user response:

The parameter in try-catch is an Object, not necessarily an exception. Depending on how await authRepo.login(); handles exceptions, that will be the type of e in the try-catch

In one of the examples here, you can see it throws a String instead of an exception

Future<void> printOrderMessage() async {
  try {
    print('Awaiting user order...');
    var order = await fetchUserOrder();
    print(order);
  } catch (err) {

    // You can see the runtimeType of err is a String 
    // because fetchUserOrder throws a String

    print('Caught error: $err');
  }
}

Future<String> fetchUserOrder() {
  // Imagine that this function is more complex.
  var str = Future.delayed(
      const Duration(seconds: 4),

      // Here it throws a string, not an exception. 
      // You could throw the exception here

      () => throw 'Cannot locate user order');
  return str;
}

Future<void> main() async {
  await printOrderMessage();
}
  •  Tags:  
  • Related