Reputation: 905
We have many try-catch blocks in our code handling the exceptions of the api calls. Since most of the catch blocks are identical we want to refactor them and only them (because the try blocks should stay in the place they are). How is this possible in Flutter?
Example code:
try {
_userData = apiService.call("user_data");
} on ResourceNotFoundException {
handleResourceNotFoundException();
} on NetworkException {
handleNetworkException();
}
Upvotes: 0
Views: 439
Reputation: 452
In case of repetitive try catch blocks, using a generic function to handle errors in one place would be also a convenient solution.
Future<T> _fetchDataAndHandleErrors<T>(Future<T> Function() callback) async {
try {
return await callback();
} on ResourceNotFoundException {
handleResourceNotFoundException();
} on NetworkException {
handleNetworkException();
}
...
}
In your case, you would invoke _fetchDataAndHandleErrors
function like this:
Future<UserData> getUserData() async {
return await _fetchDataAndHandleErrors(
() async {
userData = apiService.call("user_data");
return userData;
},
);
}
Upvotes: 1
Reputation: 905
The best solution I found is using a general catch
, fit everything into a handleException
function, and in there rethrow the exception again.
try {
_userData = apiService.call("user_data");
} on catch (e) {
handleException(e);
}
void handleException(e) {
try {
throw e;
} on ResourceNotFoundException {
handleResourceNotFoundException();
} on NetworkException {
handleNetworkException();
}
}
This way it is possible to reuse the exception handling logic and also extend it.
Upvotes: 3
Reputation: 471
You should add some abstraction to your API call, meaning you should add a function that takes in the API call you are trying to call as a parameter and surround it with a try-catch block and handle all your exceptions there.
This way you have separated your API calls logic from handling exceptions.
Upvotes: 0