【发布时间】:2020-11-24 22:33:43
【问题描述】:
我有一个简单的用户身份验证功能。当用户点击Login buttonm 时,回调会从SecurityBloc 调用login 方法,而后者又会调用ApiProvider 的execute 方法。
如果用户输入错误的密码而不是方法 _handleResponse 抛出 ApiException 并带有错误描述,我希望在 SecurityBloc 的方法 login 中捕获该错误描述。当我在 web 下运行项目时,它按预期工作。我看到带有错误消息的快餐栏。
我在 Android 下运行项目时出现问题。当用户输入错误的密码而不是 VS Code(我使用它)停止在线 throw ApiException('invalid authentication response');,即调试器认为此异常未处理!但它被捕获和处理(见代码)。当我单击调试器控制面板上的按钮continue 时,突出显示的行会跳过代码,最后我会在snackbar 中看到错误消息。
那么是否可以跳过(修复)这种情况?也许它知道错误并且有解决方法?
附:如果我选中“未捕获的异常”复选框看起来不错,但事实并非如此,因为现在我可能会传递真正未捕获的异常。
有什么想法吗?
class ApiProvider {
/// Executes HTTP request
Map<String, dynamic> execute(url, query, ...) async {
final response = await http.post(url,query:query);
return _handleResponse(response);
}
/// Parses HTTP response
Map<String, dynamic> _handleResponse(Response response) {
if (!response.contains('user')) {
throw ApiException('invalid password');
}
... // other statements
}
}
class SecurityBloc {
Future<AuthEvent> login(String user, String password) async {
try {
final data = api.execute()
if (data == null) {
throw ApiException('invalid authentication response');
}
final token = _parseData(data); // Can throws FormatException
return AuthEvent.ok(token);
} on ClientException catch(e) {
return AuthEvent.error(e.message);
} on FormatException catch(e) {
return AuthEvent.error(e.message);
} on ApiException catch(e) {
return AuthEvent.error(e.message);
}
}
}
class _LoginState extends State<Login> {
final securityBloc = SecutiryBloc();
@override
Widget build(BuildContext context) {
return
...
FlatButton(
child: Text('Login'),
onPressed: () async {
final authEvent = await securityBloc.login(...);
if (authEvent.failed) {
ScaffoldMessenger.of(context).showSnackbar(...); // Show authentication error
} else {
// access granted
}
},
),
...
}
【问题讨论】:
标签: flutter exception async-await try-catch