How to stop dio get when the internet is off? - flutter

the request is just waiting and not resulting an error, i want an error to be produced when there is no internet but it's just waiting forever
i tried
sendTimeout: 600000,
receiveTimeout: 600000,
but same result
vscode screenshot

You need to wrap your logic inside try/catch block.
try {
var response = await _dio.getUri(
Uri.parse(uri));
if (response.statusCode == 200) {
return response.data;
} else {
throw response;
}
} on SocketException catch (e) {
throw SocketException(e.toString());
} on FormatException catch (_) {
throw FormatException("Unable to process the data");
} catch (e) {
throw e;
}

Related

httpClient Request can not catch the error in flutter

here when i try to catch the error when i try to use the request without internet i can not catch the error for dealing with thim.
var httpClient = HTTP.Client();
var request = HTTP.Request("GET", Uri.parse(url));
request.headers.addAll({'Range': 'bytes=$downloadFrom-$downloadUntil'});
var response;
try{
response = httpClient.send(request).catchError((error){ throw error;});
}catch(e){
print("----> " + e.toString());
}
As according to this post: How do I check Internet Connectivity using HTTP requests(Flutter/Dart)?
I quote:
You should surround it with try catch block, like so:
import 'package:http/http.dart' as http;
int timeout = 5;
try {
http.Response response = await http.get('someUrl').
timeout(Duration(seconds: timeout));
if (response.statusCode == 200) {
// do something
} else {
// handle it
}
} on TimeoutException catch (e) {
print('Timeout Error: $e');
} on SocketException catch (e) {
print('Socket Error: $e');
} on Error catch (e) {
print('General Error: $e');
}
Socket exception will be raised immediately if the phone is aware that there is no connectivity (like both WiFi and Data connection are turned off).
Timeout exception will be raised after the given timeout, like if the server takes too long to reply or users connection is very poor etc.
Also don't forget to handle the situation if the response code isn't = 200.

How to access message in DioError

How can I access the "Message" field inside the e
My postRequest function:
Future<Response> postRequest(String endPoint, dynamic data) async {
Response response;
try {
if (data != null) {
response = await _dio!.post(endPoint, data: data);
} else {
response = await _dio!.post(endPoint);
}
} catch (e) {
//I can reach the message from here and return it, but this
is not what I want to do.
if (e is DioError) print(e.response);
throw Exception(e);
}
return response;
}
where I want to reach the message:
var response;
try{
response = await http.postRequest("Stok/$type", requestObj);
}catch(e){
print("message....: $e");
}
Future<Response> postRequest(String endPoint, dynamic data) async {
Response response;
try {
if (data != null) {
response = await _dio!.post(endPoint, data: data);
} else {
response = await _dio!.post(endPoint);
}
return response;
} on DioError {
rethrow; // or throw e;
}
}
Now, just call it like that
var response;
try{
response = await http.postRequest("Stok/$type", requestObj);
} on DioError catch(e){
print("message....: ${e.message}");
}

catchError and "try - catch" is not working (async)

My code is trying to communicate using Socket, but I can't seem to catch the exception.
I've tried these things, but they don't work and I get an exception on the IDE.
Socket socket;
try {
socket = await Socket.connect(ip, port);
// Instead of jumping to errorProcess(), the IDE will show an exception here...
} catch(e) {
errorProcess(e);
}
Socket socket = await Socket.connect(ip, port).catchError((e) {
errorProcess(e);
// catchError says we need to return FutureOr<Socket>...
});
How can I catch exceptions?
Try adding SocketException for your try catch statement.
Example Code:
try {} on SocketException catch (e) {
print(e);
} catch (e) {
print(e);
}

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.
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

How to catch http.get (SocketException)

I'm new to Flutter & Dart, trying to complete my first app.
I can't catch (with try-catch block) http.get SocketException (which happens when you call API and WiFi turned off)
I tried everything on the internet without luck, I even tried (Dio) package to catch this exception, but no success.
How to reproduce: use bottom code...turn off phone's WiFi...call API...now the app crashes with (SocketException) in your IDE.
Image: https://imgur.com/bA0rKEN
here is my simple code (updated)
RaisedButton(
child: Text("Call API"),
onPressed: () async {
try {
http.Response response = await getLoginResponse();
//do something with response
print(response.body);
} catch (e) {
print("Button onPressed Error: " + e.toString());
}
},
)
//---------------------------------------------------------------
Future<http.Response> getLoginResponse() {
return http.get(loginUrl).timeout(Duration(seconds: 10))
.then((response) {
return response;
}, onError: (e) {
print("onError: " + e.toString());
}).catchError((err) {
print("catchError: " + err.toString());
return null;
});
}
You can catch several types of errors and handle each one separately
Example:
import 'dart:io' as Io;
http.Client client = http.Client();
try {
response = await client.get(url).timeout(new Duration(seconds: 10));
} on Io.SocketException catch (_) {
throw Exception('Not connected. Failed to load data');
} on TimeoutException catch (_) {
throw Exception('Not connected. TimeOut Exception');
} catch (e) {
// Default error handling;
}
if you want to get catch in RaisedButton's try-catch block, instead of return null in getLoginInfo() methods, you must return an Exception like this:
Future<List<LoginObject>> getLoginInfo() async {
try {
List<LoginObject> loginObjectList = List<LoginObject>();
http.Response loginResponse =
await http.get(loginUrl).timeout(Duration(seconds: 10));
if (loginResponse.statusCode == 200) {
loginObjectList = loginObjectFromJson(loginResponse.body);
return loginObjectList;
} else {
throw Exception('Authentication Error');
}
} catch (e) {
print("Error: " + e.toString());
return throw Exception('Connection Error');;
}
}
Note: If you want to handle each one of error response, you can create an custom ErrorModelClass and handle error state with it and finally return your ErrorModelClass.
catch (error) {
print(error);
throw error is HttpResponseError ? error : HttpResponseError(0,"error connection");
HttpResponseError is my custom model class.