How do I return error from a Future in dart? How do I return error from a Future in dart? dart dart

How do I return error from a Future in dart?


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"));


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  }}


//POST

Future<String> post_firebase_async({String? path , required Product product}) async {    final Uri _url = path == null ? currentUrl: Uri.https(_baseUrl, '/$path');    print('Sending a POST request at $_url');    final response = await http.post(_url, body: jsonEncode(product.toJson()));    if(response.statusCode == 200){      final result = jsonDecode(response.body) as Map<String,dynamic>;      return result['name'];    }    else{      //throw HttpException(message: 'Failed with ${response.statusCode}');      return Future.error("This is the error", StackTrace.fromString("This is its trace"));    }  }

Here is how to call:

  final result = await _firebase.post_firebase_async(product: dummyProduct).  catchError((err){    print('huhu $err');  });