Home > Software engineering >  Flutter: How do I avoid repetition of try-catch-exception?
Flutter: How do I avoid repetition of try-catch-exception?

Time:10-14

This is the code I want to avoid repeating. If possible also try block.

try {
//
    } on TimeoutException catch (e) {
      log('Timeout Error: $e');
      rethrow;
    } on SocketException catch (e) {
      log('Socket Error: $e');
      rethrow;
    } on Error catch (e) {
      log('General Error: $e');
      rethrow;
    } catch (e) {
      log('All other Errors: $e');
      rethrow;
    }

CodePudding user response:

You could define a function like:

void tryCatch(Function f) {
  try {
    f();
  } on TimeoutException catch (e) {
    log('Timeout Error: $e');
    rethrow;
  } on SocketException catch (e) {
    log('Socket Error: $e');
    rethrow;
  } on Error catch (e) {
    log('General Error: $e');
    rethrow;
  } catch (e) {
    log('All other Errors: $e');
    rethrow;
  }
}

and then anywhere you want to use it do

tryCatch((){
  //your code here
});

CodePudding user response:

One trivial answer could be to refactor that try-catch cascade in a dedicated function or class, in which you return the value if everything's all right, or handle the corresponding error.

I guess yours is just an example code, but if you're just interested in logging an error and then rethrow, you don't need to distinguish between those exceptions and errors.

You can easily retrieve your error's type like so:

try {
  // some risky code
} catch(error, stackTrace) {
  print(error.runtimeType);
  print(error);  // calls its internal toString() method
  rethrow;
}

Even the above example could be refactored in a dedicated function or class, by the way.

If you're looking into something even more specific let me know, because I'm kinda curious about this, too.

  • Related