jakub
jakub

Reputation: 3844

Cut verbosity of try-catch block in Dart

I have a lot of network calls and try-catch blocks are pretty verbose, what the best way to cut on this boilerplate? I would like to replace sth like that

  Future<Something> getSomething(String id) async {
    try {
      return await _api.getSomething(id);
    } on DioError catch (error) {
      return Future.error(error.formattedMessage);
    }
  }

to be able to call sth like

  Future<Something> getSomething(String id) async {
    networkCall { _api.getSomething(id); }
  }

Is there construction in Dart that will let me achieve that?

Upvotes: 2

Views: 135

Answers (1)

Ben Konyi
Ben Konyi

Reputation: 3219

No, there's no language feature that does what you're looking for.

If you just want the function to complete with the DioError and don't need to create a new exception, you can just remove the try/catch block and let the caller handle the error.

If you do want to do some processing on a specific type of exception frequently, you can always write a wrapper method to do that:

Future<T> handleDioError<T>(Future<T> Function() f) async {
  try {
    return await f();
  } on DioError catch(e) {
    return Future.error(error.formattedMessage);
  }
}

Which you'd use like this:

Future<Something> getSomething(String id) async {
  return await handleDioError(() => _api.getSomething(id));
}

Upvotes: 3

Related Questions