Home > Back-end >  Exception thrown in stream callback is not being passed to onError callback
Exception thrown in stream callback is not being passed to onError callback

Time:10-05

I have some bluetooth connection code in my Flutter app.

I have provided an one rror callback to the stream.listen() method. The device.connect() call is throwing an exception, but one rror 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();
        }
      },
      one rror: (error) {
        print(error); // never prints
      }
    );

CodePudding user response:

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');
    },
    one rror: (_) {
      print('Caught the error');
    },
  );
}

Here the error is caught.

However if you what 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');
      }
    },
    one rror: (_) {
      print('Caught the error');
    },
  );
}
  • Related