'Exception thrown in stream callback is not being passed to onError callback

I have some bluetooth connection code in my Flutter app.

I have provided an onError callback to the stream.listen() method. The device.connect() call is throwing an exception, but onError is never called, the VSCode extension is treating that exception as an uncaught exception.

How am I supposed to catch the exception in this case?

    var stream = FlutterBlue.instance.scan();
    var sub = stream.listen(
      (scanResult) async {
        if (scanResult.device.name == _beacon.id) {
          device = scanResult.device;
          await device.connect();
        }
      },
      onError: (error) {
        print(error); // never prints
      }
    );


Solution 1:[1]

The onError parameter of the Stream.listen method catches error which happens inside the Stream. Here is a small example:

void main() {
  final _stream = Stream.fromFuture(
    Future.delayed(
      Duration(seconds: 1),
      () {
        throw 'Error';
      },
    ),
  );

  _stream.listen(
    (_) {
      print('Got an event');
    },
    onError: (_) {
      print('Caught the error');
    },
  );
}

Here the error is caught.

However if you want to catch on error inside the first callback you have to use the classic try-catch:

void main() {
  final _stream = Stream.value(0);

  _stream.listen(
    (_) {
      try {
        print('Got an event');
        throw 'Error';
      } catch (_) {
        print('Caught an error inside event listen');
      }
    },
    onError: (_) {
      print('Caught the error');
    },
  );
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1