Book Image

DART Cookbook

By : Ivo Balbaert
Book Image

DART Cookbook

By: Ivo Balbaert

Overview of this book

Table of Contents (18 chapters)
Dart Cookbook
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

Error handling with Futures


This recipe shows you how to handle errors comprehensively when working with Futures. The accompanying code future_errors.dart (inside the bin map in the future_errors project) illustrates the different possibilities; however, this is not a real project, so it is not meant to be run as is.

Getting ready

When the function that returns a Future value completes successfully (calls back) signaled in the code by then, a callback function handleValue is executed that receives the value returned. If an error condition took place, the callback handleError handles it. Let's say this function is getFuture(), with Future as the result and a return value of type T, then this becomes equivalent to the following code:

Future<T> future = getFuture();
future.then(handleValue)
.catchError(handleError);

handleValue(val) {
  // processing the value
}

handleError(err) {
  // handling the error
}

The highlighted code is sometimes also written as follows, only to make the return...