dart - 具有非异步功能的 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 块中被捕获吗?
解决方案
是的,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 与你的函数是否会被捕获无关,所以最好使用第二个选项。
推荐阅读
- java - 无法在 GluonMobile 中为 ToggleButton 设置边框
- node.js - 为什么我不能停止“node-cron”作业?
- python - Plotly Gantt 回调和点击事件
- google-chrome-extension - 我如何在 chrome 扩展(清单 V3)的服务人员中包含一个 socket.io-client
- powershell - 如何仅选择“foreach”中的 3 个最新文件
- python - 如何在不指定年份的情况下按日期范围过滤熊猫数据框
- node.js - 并且偶尔会在 shell 和节点本机驱动程序上产生错误的结果
- r - 如何在 .asp 类型的网站上使用 RSelenium 或 Rvest 在网页上登录非 html 类型的服务器?
- flutter - 如何在页面上制作 Navigator.of(context).pop 并在 Flutter 上重置它
- c# - 成功认证后,Asp MVC URL 不重定向到索引