Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dart / Flutter - Debugger stops on caught exceptions

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;
    }
  }
like image 676
TheGeekZn Avatar asked Jun 28 '19 07:06

TheGeekZn


People also ask

How do you use a dart try catch?

The try / on / catch Blocks The on block is used when the exception type needs to be specified. The catch block is used when the handler needs the exception object. The try block must be followed by either exactly one on / catch block or one finally block (or one of both).

How to use breakpoint in Flutter?

To set a breakpoint, click the left margin (the line number ruler) in the source area. Clicking once sets a breakpoint, which should also show up in the Breakpoints area on the left. Clicking again removes the breakpoint.


2 Answers

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

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).

like image 121
Danny Tuppeny Avatar answered Sep 20 '22 02:09

Danny Tuppeny


Here is a supplemental image (VS Code) to the Danny's answer:

enter image description here

like image 38
Suragch Avatar answered Sep 17 '22 02:09

Suragch