How do I return error from a Future in dart?

Throwing an error/exception:

You can use either return or throw to throw an error or an exception.

  • Using return:
    Future<void> foo() async {
      if (someCondition) {
        return Future.error('FooError');
      }
    }
    
  • Using throw:
    Future<void> bar() async {
      if (someCondition) {
        throw Exception('BarException');
      }
    }
    

Catching the error/exception:

You can use either catchError or try-catch block to catch the error or the exception.

  • Using catchError:
    foo().catchError(print);
    
  • Using try-catch:
    try {
      await bar();
    } catch (e) {
      print(e);
    }
    

You can return the error data like this if you want to read the error object:

response = await dio.post(endPoint, data: data).catchError((error) {
  return error.response;
});
return response;

You can use throw :

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 
       throw("some arbitrary error"); // error thrown
  }
}