How to Catch Exception In Flutter?

3 min read
How to Catch Exception In Flutter
How to Catch Exception In Flutter

If you want to find out the exact type of error you are getting, remove the exception so that all errors are caught, put a breakpoint within the catch, and check the type of error. so in this article, we will go through How to Catch Exception In Flutter

How to Catch Exception In Flutter?

Try with the below code snippet:

void loginUser(String email, String password) async {
  try {
    var user = await _data
      .userLogin(email, password);
    _view.onLoginComplete(user);
      });
  } on FetchDataException catch(e) {
    print('error caught: $e');
    _view.onLoginError();
  }
}

catchError is sometimes a bit tricky to get right. With async/await you can use try/catch like with sync code and it is usually much easier to get right.

To handle errors in an async and await function, use try-catch:

Run the following example to see how to handle an error from an asynchronous function.

Future<void> printOrderMessage() async {
  try {
    var order = await fetchUserOrder();
    print('Awaiting user order...');
    print(order);
  } catch (err) {
    print('Caught error: $err');
  }
}

Future<String> fetchUserOrder() {
  // Imagine that this function is more complex.
  var str = Future.delayed(
      Duration(seconds: 4),
      () => throw 'Cannot locate user order');
  return str;
}

Future<void> main() async {
  await printOrderMessage();
}

Within an async function, you can write try-catch clauses the same way you would in synchronous code.

You can also refer to the code snippet like below:

Future < User > userLogin(email, password) async { try {
  Map body = {
    'username': email,
    'password': password
  };
  http.Response response = await http.post(apiUrl, body: body);
  final responseBody = json.decode(response.body);
  final statusCode = response.statusCode;
  if (statusCode != HTTP_200_OK || responseBody == null) {
    throw new FetchDataException(
      "An error occured : [Status Code : $statusCode]");
   }
  return new User.fromMap(responseBody); }
   catch (e){
    print(e.toString());
}

Conclusion:

Thanks for being with us on a Flutter Journey !!!

So in this article, We have been through How to Catch Exception In Flutter.

Keep Learning !!! Keep Fluttering !!!

Let us know in the comments if you are still facing any problems in Flutter development!! We are here to help you 馃檪

Flutter Agency聽is our portal Platform dedicated to Flutter Technology and聽Flutter Developers. The portal is full of cool resources from Flutter like聽Flutter Widget聽Guide,聽Flutter Projects,聽Code libs聽and etc.

Flutter Agency聽is one of the most popular online portals dedicated to聽Flutter Technology and daily thousands of unique visitors come to this portal to enhance their knowledge of聽Flutter.

Leave a Reply