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) );
You can use CancelableOperation or CancelableCompleter to cancel a future.
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.
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.
You can use either return
or throw
to throw an error or an exception.
return
:Future<void> foo() async { if (someCondition) { return Future.error('FooError'); } }
throw
:Future<void> bar() async { if (someCondition) { throw Exception('BarException'); } }
You can use either catchError
or try-catch
block to catch the error or the exception.
catchError
:foo().catchError(print);
try-catch
:try { await bar(); } catch (e) { print(e); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With