Future is used to indicate values or errors that may occur in the Future. Callbacks can be registered to handle returns or errors. For example,

    Future<int> future = getFuture();
    future.then((value) => handleValue(value))
          .catchError((error) => handleError(error));
Copy the code

Sometimes you can use a future to accept a value or error from another future.

Future<int> successor = future.then((int value){ return 42; }, onError: (e){ if(canHandle(e)){ return 499; } else { throw e; }});Copy the code

If a Future fails before it owns the recipient, the recipient’s catchError will be caught by the global error-handler to prevent the exception from being silently deleted. This means that error handlers should be registered in advance to handle errors in a timely manner. The following examples address the potential above problems:

var future = getFuture(); new Timer(Duration(millisecords: Future.then ((value){userValue(vale)}, onError (e){handleError(e)}); });Copy the code

Usually we need to register two callbacks for a Future to increase its readability.

Future future = Future(foo); future.then((value) => handleValue(value)).catchError((e) => handleError(e)); Future = Future(foo); future.then((value) => handleValue(value),onError(e) => handleError(e));Copy the code

The first catches the exception of foo and handleValue(value). The second focuses only on foo’s exception.

Try catch for a particular scenario

Future<void> foo() async{ throw Exception('1'); } Future<void> foo1(){ throw Exception('2'); } Future<void> foo2(){ throw Exception('3'); } void main() async{ foo().catchError((e) => handleError(e)); foo1().catchError((e) => handleError(e)); try { await foo2(); } catch (e) { print(e); }}Copy the code

Emitted by foo1(), the dilemma that exceptions continue to exist even though they are not trapped by a catch still exists. If async is not added, the throw will not be considered a Future submission error, but a synchronization error. You need to use synchronous try catch like foo2. To make the code more readable, if we need to throw an exception in the Future, we should use the following method:

Future<void> foo3(){
 reture Future.error(Exception('4')) ;
}
Copy the code