Search code examples
dartdart-async

Async/future error handling in Dart not working as expected


I've been at this for hours studying the Futures and Error Handling section on the Dart page without any luck. Can anyone explain why the code below does not print All good?

import 'dart:async';

main() async {
  try {
    await func1();
  } catch (e) {
    print('All good');
  }
}

Future func1() {
  var completer = new Completer();
  func2().catchError(() => completer.completeError('Noo'));
  return completer.future;
}

Future func2() {
  var completer = new Completer();
  completer.completeError('Noo');
  return completer.future;
}

Solution

  • In func1 the function used as catchError parameter must be a subtype of type (dynamic) => dynamic regarding the error:

    Unhandled exception:

    type '() => dynamic' is not a subtype of type '(dynamic) => dynamic' of 'f'.

    Thus you should use:

    Future func1() {
      var completer = new Completer();
      func2().catchError((e) => completer.completeError('Noo'));
      return completer.future;
    }
    

    You don't get any analyzer error because the parameter is typed with Function. You can file an issue to know why the type is not a more specific type matching (dynamic)=>dynamic