arrmani88
arrmani88

Reputation: 1072

What's the best practice to throw an Exception in Flutter

I have an exception that gets thrown multiple times before getting handled in my code, (the same error object gets thrown 4 times in the tree).

During each throw , flutter appends the word Exception: to my error object, so the final shape of the message is:
Exception: Exception: Exception: Exception: SocketException: OS Error: Connection refused, errno = 111, address = 10.12.7.15, port = 39682

And this is an example of how I handle exceptions:

getSomeData () async {
  try {
    await myFunction3();
  } catch (e) {
    throw Exception(e);
  }
}
/*****************************************/
Future<void> myFunction3 () async {
  try {
    await myFunction2();
  } catch (e) {
    throw Exception(e);
  }
}
/*****************************************/
Future<void> myFunction2 () async {
  try {
    await myFunction1();
  } catch (e) {
    throw Exception(e);
  }
}
/*****************************************/
Future<void> myFunction1() async {
  try {
    await dio.get(/*some parameters*/);
  }
  on DioError catch (e) {
    throw Exception(e.error);
  }
  catch (e) {
    throw Exception(e);
  }
}

I want to throw the Exception() in a right way so the repetition of word Exception: doesn't appear anymore in my error string.

Upvotes: 2

Views: 3673

Answers (1)

Andrey Gordeev
Andrey Gordeev

Reputation: 32449

Instead of throwing a new exception, you could rethrow the catched one:

Future<void> myFunction1() async {
  try {
    await dio.get(/*some parameters*/);
  }
  on DioError catch (e) {
    // do something
    rethrow;
  }
  catch (e) {
    // do something
    rethrow;
  }
}

See more: https://dart.dev/guides/language/effective-dart/usage#do-use-rethrow-to-rethrow-a-caught-exception

Upvotes: 2

Related Questions