0
void main() {
  foo().catchError((error) {
    if (error is Future) {
      error.then((value) => print('value = $value'));
    }
  });
}

Future<void> foo() async {
  throw Future.error('FooError');
}

The error is caught inside catchError but I am not able to retrieve the value of Future.error which is FooError in this example.

iDecode
  • 22,623
  • 19
  • 99
  • 186
  • Why would you do that? Either return the Future.error, or throw the error directly without the Future? – nvoigt Aug 25 '20 at 11:34

2 Answers2

0

Well that's Future.error so you'll have to again use catchError on it.

void main() {
  foo().catchError((error) {
    if (error is Future) {
      error.catchError((error) => print(error)); // prints 'FooError'
    }
  });
}

Future<void> foo() async {
  throw Future.error('FooError');
}
iDecode
  • 22,623
  • 19
  • 99
  • 186
0

You just don't, there is no point in doing so.

You can either throw the error:

void main() {
  foo().catchError((error) {
    print('error = $error');
  });
}

Future<void> foo() async {
  throw 'FooError';
}

Or if that is for whatever reason not convinient, you can use Future.error to create a Future that will have an error already:

void main() {
  foo().catchError((error) {
    print('error = $error');
  });
}

Future<void> foo() {
  return Future.error('FooError');
}

But actually throwing a Future.error is redundant and not useful.

nvoigt
  • 75,013
  • 26
  • 93
  • 142
  • Yes, you're right. Actually I had [this question](https://stackoverflow.com/q/63560652/12483095) and someone provided an answer to it, but when I was printing it on console, I was seeing `Instance of Future`, so I decided to use `then` on that `error` but it wasn't printing the value, so I released I had to again use `catchError` on it. – iDecode Aug 25 '20 at 11:42
  • So, this post doesn't have any significance in real world problems as you should `return Future.error` instead of throwing it. You can however throw an `Exception` and that would work just fine. – iDecode Aug 25 '20 at 11:44
  • Well, yeah. Instead of describing how to handle a bad piece of code, just don't write a bad piece of code in the first place. – nvoigt Aug 25 '20 at 11:51