【问题标题】:Exception handling in flutter + VS CodeFlutter + VS Code 中的异常处理
【发布时间】:2020-11-24 22:33:43
【问题描述】:

我有一个简单的用户身份验证功能。当用户点击Login buttonm 时,回调会从SecurityBloc 调用login 方法,而后者又会调用ApiProviderexecute 方法。

如果用户输入错误的密码而不是方法 _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


    【解决方案1】:

    请查看我提出的https://github.com/FirebaseExtended/flutterfire/issues/3475...如果您关注该主题和最后的链接,则似乎修复已在 10 月初发布给 master ....不知道什么时候会它通过发布来稳定。但基本上,这是一个影响 IDE 的问题,并且不会在设备上发布的应用程序中体现出来。

    【讨论】:

    • 这回答了你的问题吗?
    猜你喜欢
    • 2019-07-02
    • 1970-01-01
    • 1970-01-01
    • 2017-12-30
    • 2021-01-03
    • 2023-04-03
    • 2023-03-13
    • 2020-11-29
    • 1970-01-01
    相关资源
    最近更新 更多