Firebase 身份验证期望未被 catch 捕获

问题描述 投票:0回答:1

使用错误的凭据登录时,会按预期抛出

Exception
。然而,
catch block
未能赶上
Exception
,导致崩溃。

发生异常。 FirebaseAuthException ([firebase_auth/invalid-credential] 提供的身份验证凭据是 不正确、格式错误或已过期。)

void signInWithEmail(String email, String password) async {
  state = state.copyWith(isLoading: true);
  try {
    UserCredential result = await _auth.signInWithEmailAndPassword(email: email.trim(), password: password.trim());
    state = state.copyWith(user: await _createMyUserFromFirebaseUser(result.user!), isLoading: false);
  } on FirebaseAuthException catch (e) {
    state = state.copyWith(isLoading: false, error: e.toString());
  } on PlatformException catch (_) {} catch (_) {}
}

我发现其他人提到过这个问题,但从未找到解决方案。正如你所看到的,我尝试指定要捕获的异常,但不知何故它从未被捕获。

flutter firebase dart firebase-authentication
1个回答
0
投票

我创建了一个简化的示例来展示可能正在发生的事情:

typedef State = ({String userName, bool isLoading, String error});

State state = (userName: 'not set', isLoading: true, error: 'nothing');

void signInWithEmail({
  required String email,
  required String password,
  Function? errorCallback,
}) async {
  if (errorCallback == null) {
    final userName = await Future.delayed(Duration.zero, () => 'Nick2001');
    state = (userName: userName, isLoading: false, error: 'nothing');
  } else {
    throw errorCallback();
  }
}

void main() async {
  try {
    signInWithEmail(
      email: '[email protected]',
      password: '1234',
      errorCallback: () => 'User not registered.',
    );
    print(state);
  } catch (e) {
    print('Caught error in main:');
    print('  $e');
  }
}

即使设置了 catch 块来捕获每个可能的异常,该程序也会生成以下控制台输出。

$ dart main.dart
State: (error: nothing, isLoading: true, userName: not set)
Unhandled exception:
Exception: User not registered.
#0      signInWithEmail (file:///work/main.dart:14:5)
#1      main (file:///work/main.dart:20:5)
#2      _delayEntrypointInvocation.<anonymous closure> (dart:isolate-patch/isolate_patch.dart:297:19)
#3      _RawReceivePort._handleMessage (dart:isolate-patch/isolate_patch.dart:184:12)

现在我们更改函数

signInWithEmail
的签名以返回
Future<void>
并在 main 中等待该函数:

Future<void> signInWithEmail({
  required String email,
  required String password,
  Function? errorCallback,
}) async {
  if (errorCallback == null) {
    final userName = await Future.delayed(Duration.zero, () => 'Nick2001');
    state = (userName: userName, isLoading: false, error: 'nothing');
  } else {
    throw errorCallback();
  }
}

void main() async {
  try {
    await signInWithEmail(
      email: '[email protected]',
      password: '1234',
      errorCallback: () => Exception('User not registered.'),
    );
    print('State: $state');
  } catch (e) {
    print('Caught error in main:');
    print('  $e');
  }
}

运行该程序会产生预期的输出:

Caught error in main:
  Exception: User not registered.

有关详细说明,请参阅处理标记为异步的 void Dart 函数中的错误

© www.soinside.com 2019 - 2024. All rights reserved.