Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I return error from a Future in dart?

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) ); 
like image 486
Kingsley CA Avatar asked Feb 01 '19 07:02

Kingsley CA


People also ask

How do you cancel a Future in darts?

You can use CancelableOperation or CancelableCompleter to cancel a future.

How do you throw a Dart error?

Throwing an ExceptionThe throw keyword is used to explicitly raise an exception. A raised exception should be handled to prevent the program from exiting abruptly.

How do you use the Future in darts?

A future (lower case “f”) is an instance of the Future (capitalized “F”) class. A future represents the result of an asynchronous operation, and can have two states: uncompleted or completed. Note: Uncompleted is a Dart term referring to the state of a future before it has produced a value.


1 Answers

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); } 
like image 160
CopsOnRoad Avatar answered Sep 19 '22 00:09

CopsOnRoad