我正在尝试使用flutter-fire软件包执行Firebase Phone身份验证(使用SMS),但是在“验证”过程中检查错误情况时遇到了一些障碍。
一个注意事项:投掷发生在ChangeNotifierProvider中,捕获发生在使用提供程序获取状态数据的单独小部件中。
当我尝试调试时,我看到抛出了错误,但是catch块没有被调用。
这是引发错误的地方(PhoneVerificationFailed函数):
`
Future<void> verifyPhoneNumber(String phoneNumber) async {
print("Verify Phone Number called");
final PhoneCodeAutoRetrievalTimeout autoRetrieve = (String verId) {
this._verificationID = verId;
};
final PhoneCodeSent smsCodeSent = (String verId, [int forceCodeResend]) {
this._verificationID = verId;
print("SMS Sent");
this.smsSent = true;
notifyListeners();
throw (HttpException("Test"));
};
final PhoneVerificationCompleted verificationSuccessful =
(AuthCredential user) {
print("verified");
};
final PhoneVerificationFailed verificationFailed =
(AuthException exception) {
print("failed, ${exception.message}");
throw (exception);
};
this._phoneNumber = phoneNumber;
notifyListeners();
var result = await FirebaseAuth.instance.verifyPhoneNumber(
phoneNumber: phoneNumber,
codeAutoRetrievalTimeout: autoRetrieve,
codeSent: smsCodeSent,
timeout: const Duration(seconds: 0),
verificationCompleted: verificationSuccessful,
verificationFailed: verificationFailed,
);
return result;
}`
这是我的捕获代码:
`Future<void> _submitPhoneNumber() async {
_formKey2.currentState.save();
setState(() {
_isLoading = true;
});
try {
await Provider.of<Auth>(context, listen: false)
.verifyPhoneNumber(_authData['phoneNo']);
setState(() {
_isLoading = false;
});
} catch (error) {
print("Exception caught ${error.message}");
errorSnackBar(error.message, "Close");
}
}
`
Edit:我正在https://dart.dev/codelabs/async-await#example-async-and-await-with-try-catch中的代码游乐场里玩耍,我看到只有Future返回某些内容时才捕获异常,即使返回类型为Future。这可能是根本原因吗?
答案 0 :(得分:0)
您需要捕获抛出的异常。
try {
await Provider.of<Auth>(context, listen: false)
.verifyPhoneNumber(_authData['phoneNo']);
setState(() {
_isLoading = false;
});
} on HttpException catch (e) { // add on HttpException
print("Exception caught ${error.message}");
errorSnackBar(error.message, "Close");
}
}