httpClient Request can not catch the error in flutter - 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.

Related

How to stop dio get when the internet is off?

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;
}

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);
}

Handling exception HTTP request flutter

I want to handle http request flutter with some error message but I got so many errors here. I just make it based on the suggestion but it didn't work for me. Please, anyone, help me
Here is my function to call API
getData(data, apiUrl) async {
var tempUrl = _url + apiUrl + await _getToken();
Uri uri = Uri.parse(tempUrl);
var fullUrl = uri.replace(queryParameters: data);
var res;
try {
var response = await http.get(fullUrl, headers: _setHeaders()).timeout(
const Duration(seconds: 60));
print(response.statusCode);
if (response.statusCode != 200) {
res = {
"success": false,
"status": response.statusCode,
"message": _returnResponse(response)
};
}
else {
res = response;
}
}
on SocketException {
throw FetchDataException('No Internet connection');
}
on TimeoutException catch (e) {
res = {
"success": false,
"status": response.statusCode,
"message": "Connection timeout"
};
} on Error catch (e) {
print('Error: $e');
}
return res;
}
This is my return response for the others except 200
dynamic _returnResponse(http.Response response) {
switch (response.statusCode) {
case 400:
throw BadRequestException(response.body.toString());
case 401:
case 403:
throw UnauthorisedException(response.body.toString());
case 500:
default:
throw FetchDataException(
'Error occured while Communication with Server with StatusCode : ${response
.statusCode}');
}
}
and here is my app_exception.dart I got from StackOverflow and other forums
class AppException implements Exception {
final _message;
final _prefix;
AppException([this._message, this._prefix]);
String toString() {
return "$_prefix$_message";
}
}
class FetchDataException extends AppException {
FetchDataException([String message])
: super(message, "Error During Communication: ");
}
class BadRequestException extends AppException {
BadRequestException([message]) : super(message, "Invalid Request: ");
}
class UnauthorisedException extends AppException {
UnauthorisedException([message]) : super(message, "Unauthorised: ");
}
class InvalidInputException extends AppException {
InvalidInputException([String message]) : super(message, "Invalid Input: ");
}
I have tried so many suggestions but it didn't work at all
I got this error
Error: 'SocketException' isn't a type.
on SocketException {
^^^^^^^^^^^^^^^
Error: 'TimeoutException' isn't a type.
on TimeoutException catch (e) {
^^^^^^^^^^^^^^^^
I used dio package. That's more easier and bug-less than i make it
https://pub.dev/packages/dio
If the error occurring is on SocketException and Timeout exception ensure you have imported both dart.io and dart.async respectively in that file. As pertains to you code I was able to successfully run it but you can refer to the answer by Paresh Mangukiya for a step by step or refer here for more clarification on how to handle Network calls and exceptions with custom error responses in flutter.

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.

unhandled socket exception with no internet connection when i set timeout duration

I use simple method to get some data from internet 'http get request' :
`Future<UserModel> getUser(int userId) async {
UserModel user;
try {
final response = await http.get(
"$_baseUrl/users/$userId",
)
.timeout(Duration(seconds: 5))
;
user = userModelFromJson(response.body);
return user;
} on TimeoutException catch (e) {
print('$e in authentication service');
throw e;
} on SocketException catch (e) {
print('$e in authentication service');
throw e;
} catch (e) {
print('$e in authentication service');
throw e;
}
}`
but when i have no internet connection it shows me that error :
`Exception has occurred.
SocketException (SocketException: Failed host lookup:
'jsonplaceholder.typicode.com' (OS Error: No address associated with
hostname, errno = 7))`
whenever i remove the .timeout(Duration(seconds:5)) the code works perfectly ,
but the socket exception is caught after long time (15-20)seconds to show that there is no internet connection that's why i used timeout, i tried to use multiple packages (http middleware ,http helper ,retry) , i tried to use http.client and close it in finally block and the same error occurred and the app crashes
the image shows the error when the socket exception is thrown and unhandled
it catches the timeout exception as expected but then after another 10-15 seconds it throws an handled socket exception ,why it throws this socket exception and what can i do to avoid this?
If you want to implement a timeout with the http package, here is how it can be done:
import 'dart:io';
import 'package:http/http.dart' as http;
import 'package:http/io_client.dart' as http;
Future<void> login(String email, String password) async {
final ioClient = HttpClient();
client.connectionTimeout = const Duration(seconds: 5);
final body = { 'email': email, 'password': password };
final client = http.IOClient(ioClient);
http.Response res;
try {
res = await client
.post(
'$url/login',
headers: {'Content-Type': 'application/json'},
body: jsonEncode(body));
} on SocketException catch (e) {
// Display an alert, no internet
} catch (err) {
print(err);
return null;
}
// Do something with the response...
}
You should consider using the HTTP package https://pub.dev/packages/http
as it helps cleanup your code an helps with error handling.
Here's an example of a GET request using the package :
await http.get(url).then((response) async {
// DO SOMETHING HERE
});
response.body is your data.
response.statusCode is your http status code (200, 404, 500, etc.)
https://en.wikipedia.org/wiki/List_of_HTTP_status_codes
and here's a post request with data :
var data = {
"dataset1": {
"key1": "value",
"key2": "value",
},
};
await http.post(url,
body: jsonEncode(data),
headers: {'content-type': 'application/json'}).then((response) async {
// DO SOMETHING HERE
});