首页 > 解决方案 > 具有非异步功能的 Dart 未来

问题描述

我正在使用 Dart 为 firebase phone auth 创建一个功能。有两个函数 getCredential 和 signIn。使用 try/catch 块时,我不确定应该如何编码。非异步函数getCredential应该在 try/catch 块之外还是在里面?

是否应该编码为:

  // Sign in with phone
  Future signInWithPhoneNumber(String verificationId, String smsCode) async {
    AuthCredential credential = PhoneAuthProvider.getCredential(
      verificationId: verificationId,
      smsCode: smsCode,
    );
    try {
      AuthResult result = await _auth.signInWithCredential(credential);
      FirebaseUser user = result.user;
      return user;
    } catch (e) {
      print(e.toString());
      return null;
    }
  }

还是应该这样编码?

  // Sign in with phone
  Future signInWithPhoneNumber(String verificationId, String smsCode) async {
    try {
      AuthCredential credential = PhoneAuthProvider.getCredential(
        verificationId: verificationId,
        smsCode: smsCode,
      );
      AuthResult result = await _auth.signInWithCredential(credential);
      FirebaseUser user = result.user;
      return user;
    } catch (e) {
      print(e.toString());
      return null;
    }
  }

如果编码为第二个选项,try/catch 是否仅适用于异步函数或两者兼而有之。例如,如果getCredential函数产生错误,它会在 catch 块中被捕获吗?

标签: dartasync-await

解决方案


是的,catch 会处理你的 try 块中抛出的任何东西,它不是异步特定的。为了确认这一点,您可以编写一个在尝试开始时调用的函数,例如:

// this is a function that throws
void doSomething(String param) {
   if (param == null) {
     throw FormatException('param can not be null'); 
   }
}


Future signInWithPhoneNumber(String verificationId, String smsCode) async {
  try {
    doSomething(null); // this will be caught
    AuthCredential credential = PhoneAuthProvider.getCredential(
      verificationId: verificationId,
      smsCode: smsCode,
    );
    AuthResult result = await _auth.signInWithCredential(credential);
    FirebaseUser user = result.user;
    return user;
  } catch (e) {
    print(e.toString()); // this prints 'FormatException: param can not be null'
    return null;
  }
}  

所以 async 与你的函数是否会被捕获无关,所以最好使用第二个选项。


推荐阅读