Cannot return value from future catchError

According to the https://dart.dev/guides/libraries/futures-error-handling#errors-in-the-middle-of-a-long-chain if I catch future error with catchError and return some value from it, the error should be handled and subsequent then should be triggered with the value returned from the catch error (just like js does).

When I try to do that, I am getting catch 2. TypeError: "fda": type 'JSString' is not a subtype of type 'Future<Null>' error.

Example: https://dartpad.dev/da4a4a07928759748bda80b87a22531e

Author: Fantashit

1 thought on “Cannot return value from future catchError

  1. This is working as expected. Note that onError which you pass to Future<T>.catchError is expected to return a value which is a value of type FutureOr<T>. Unfortunately it is not checked statically due to the limitations of the Dart type system (/cc @lrhn @leafpetersen). In your example:

      test.then((x) {
        print('then 1. $x');
        throw 'test';
      }).catchError((e) {
        print('catch 1. $e');
        return 'fda';
      })

    test.then(...) returns Future<Null> – this is inferred based on the type of the closure you pass to then(...). This means that onError in catchError can only return values assignable to FutureOr<Null>, while you are trying to return a String. You can add <String> to then to make it return Future<String> – which then will make your code work as expected:

    test.then<String>((x) {
      print('then 1. $x');
      throw 'test';
    }).catchError((e) {
      print('catch 1. $e');
      return 'fda';
    })

    It’s rather unfortunate that onError callback are not properly typed, but sadly this requires union types to make it work.

Comments are closed.