I have the following asynchronous function that has a timeout in case the request lasts more than 5 seconds:
Future<List<Product>> initProducts() async {
if(!productsHaveBeenInitialized){
try{
products = await ProductDatabaseService.readProducts().timeout(Duration(seconds: 5));
productsHaveBeenInitialized = true;
notifyListeners();
}on TimeoutException{
rethrow;
} catch (e){
rethrow;
}
}
return products;
}
And this is where I call it:
try{
productProvider.initProducts();
}on ClientIsOfflineException{
Navigator.of(context).pushReplacementNamed('offline');
}on TimeoutException{
NotificationsService.showSnackbar("Por favor, revise su conexión");
}catch(e){
NotificationsService.showSnackbar("Ha ocurrido un error al leer los productos");
}
The thing is that when I do the test without an internet connection, it should show a SnackBar
saying "Please check your connection" since the timeout would expire and it rethrow
would throw the exception that would handle the second try.
However, the application stops as if it rethrow
were an unhandled exception when it is. Why does this happen?
This is an image of how the text editor shows the error:
Instead, if I handle the exception in the same function if it handles the error correctly:
Future<List<Product>> initProducts() async {
if(!productsHaveBeenInitialized){
try{
products = await ProductDatabaseService.readProducts().timeout(Duration(seconds: 5));
productsHaveBeenInitialized = true;
notifyListeners();
}on TimeoutException{
NotificationsService.showSnackbar("Error en la conexión");
} catch (e){
rethrow;
}
}
return products;
}
As I was told in the comments, the problem was that if I don't use a
await
try it doesn't enter the catch. To solve it I have extracted the call to an asynchronous function: