Dart / Flutter-调试器在捕获到的异常时停止 [英] Dart / Flutter - Debugger stops on caught exceptions

查看:263
本文介绍了Dart / Flutter-调试器在捕获到的异常时停止的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在检查API端点(确定连接状态)的相对简单的代码块中,我依靠 try..catch 作为验证应用程序是否有效的机制。可以与服务器通信。

In a relatively simple block of code that checks an API endpoint (determining connection state), I rely on a try..catch as the mechanism to validate if the application can communicate with the server.

我遇到的问题是,在调试时,调试器始终在连接线上停止(当应用程序处于脱机状态),即使我

The issue I'm having is that while debugging, the debugger always stops on the connection line (when the application is offline) even though I am handling the errors internally.

  Future<bool> isOnline() async {
    try {
      // VSCode debugger always stops on this line when no connection
      await http
          .get('${consts.apiBaseUrl}/api/ping')
          .timeout(Duration(seconds: normalTimeoutLength))
          .catchError(
        (_) {
          // Trying catchError on the Future
          _isOnline = false;
          return false;
        },
      );
      _isOnline = true;
      return true;
    } on HttpException catch (_) {
      // Trying to catch HTTP Exceptions
      _isOnline = false;
      return false;
    } on SocketException catch (_) {
      // Trying to catch Socket Exceptions
      _isOnline = false;
      return false;
    }
  }


推荐答案

此是Dart VM的限制。它不能正确检测到 catchError()捕获的异常,因此会导致调试器暂停它们。这里有一些关于此的讨论:

This is a limitation of the Dart VM. It does not correctly detect exceptions that are caught with catchError() so it causes the debugger to pause on them. There's some discussion about this here:

https://github.com/flutter/flutter/issues/33427#issuecomment-504529413

如果您单击继续/继续,应该行为没有差异,但是作为一种变通办法,您可以将代码转换为使用实际的 try / catch 而不是 catchError()或取消选中调试侧栏中的选项以打破未捕获的异常(尽管显然这也会影响真正的未捕获的异常,尽管在Flutter中它们并不常见,因为框架捕获了大多数异常)。

If you click Continue/Resume there should be no difference in behaviour, but as a workaround you could convert the code to use real try/catch instead of catchError() or untick the option in the Debug side bar to break on uncaught exceptions (though obviously this will affect real uncaught exceptions too - although in Flutter they're not too common since the framework catchs most exceptions).

这篇关于Dart / Flutter-调试器在捕获到的异常时停止的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆