softshipper
softshipper

Reputation: 34071

Future throw exception handle outside from origin future

i am trying to understand, how dart future exception works. I read a very good article about it link. But when i have nested future and the first of them throw an error, how can i handle this error on the second future.

To clarify, what i mean look at the following sample.

import 'dart:async';

void main() {

  var fur1 = new Future<int>(() => 45);
  fur1.then((value) {
    throw new StateError('Hello error');
  });

  var fur2 = new Future<int>(() => 24);
  fur2.then((value) {
    fur1.then((value1) {
      print(value1);
    });
    print(value);
  }).catchError((err) => print(err));
}

In the fur1, i throw an exception and expected to catch the error in the fur2, but the compiler show message

Unhandled exception: Bad state: Hello error

It is possible to handle nested error in future? I know, i could use here the completer class, maybe it would be the solution?

Upvotes: 2

Views: 2683

Answers (1)

G&#252;nter Z&#246;chbauer
G&#252;nter Z&#246;chbauer

Reputation: 657238

I'm not sure what you actually try to accomplish.

but for me it works this way

import 'dart:async';

void main() {

  var fur1 = new Future<int>(() => 45);
//  fur1.then((value) {
//    throw new StateError('Hello error');
//  });

  var fur2 = new Future<int>(() => 24);
  fur2.then((value) {
    var x = fur1.then((value1) {
      print(value1);
        throw new StateError('Hello error'); // <= inner exception
      });
      print(value);
      return x; // <= return future
    }).catchError((err) => print('catchError: ${err}'));
  }

or this way

import 'dart:async';

void main() {

  var fur1 = new Future<int>(() => 45);
  fur1.then((value) {
    throw new StateError('Hello1 error');
  }).catchError((err) => print('catchError1: ${err}'));

  var fur2 = new Future<int>(() => 24);
  fur2.then((value) {
    var x = fur1.then((value1) {
      print(value1);
      throw new StateError('Hello2 error'); // <= inner exception
    });
    print(value);
    return x; // <= return future
  }).catchError((err) => print('catchError2: ${err}'));
}
catchError1: Bad state: Hello1 error
24
45
catchError2: Bad state: Hello2 error

Upvotes: 2

Related Questions