How do I return error from a Future in dart?

Kingsley Kbc Comics picture Kingsley Kbc Comics · Feb 1, 2019 · Viewed 14.2k times · Source

In my flutter app, I have a future that handles http requests and returns the decoded data. But I want to be able to send an error if the status code != 200 that can be gotten with the .catchError() handler.

Heres the future:

Future<List> getEvents(String customerID) async {
  var response = await http.get(
    Uri.encodeFull(...)
  );

  if (response.statusCode == 200){
    return jsonDecode(response.body);
  }else{
    // I want to return error here 
  }
}

and when I call this function, I want to be able to get the error like:

getEvents(customerID)
.then(
  ...
).catchError(
  (error) => print(error)
);

Answer

CopsOnRoad picture CopsOnRoad · Aug 31, 2019

Use return if you want the error to be caught inside catchError()

Use throw if you want the error to be caught inside try/catch.

return Future.error("This is the error", StackTrace.fromString("This is its trace"));