-
Notifications
You must be signed in to change notification settings - Fork 358
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Flutter try catch can't catch SocketException ( Exception has occurred. SocketException (SocketException: OS Error: No route to host, errno = 113) #551
Comments
same here:
tested on stable, dev, and master channels. |
I also had a similar problem in case the server still hasn't started.
If it could catch the exception and proceed logically instead of crashing the app then maybe better. |
so is there is a workaround? |
@EgHubs how did it workaround?? |
Iam asking if you solved it. |
I still haven't solved it yet 😅 |
+1 |
I got a similar issue when using At least for my issue, it seems like But I use some async code to catch the error and don't have issues with this; maybe worth trying for others with issues
|
I also encountered this with a socket exception. Quite frustrating. edit: I should clarify that I'm not just getting a random socket exception -- the method I'm calling that contains my Like flo80 said, this happens when the server in question is offline, meaning no response is possible. |
I have the same problem, but it seems to be a problem with flutter instead. From the debugger it seems that exception is coming from the dart:io package |
Can someone provide a complete minimal reproduction case and instructions to see this behavior? I have not been able to locally reproduce a case where using |
i have the same error with subdomains in localhost ( http://sub.localhost:80/example ) . But i have not in ( http://localhost:80 ), help me please. Flutter try catch can't catch SocketException ( Exception has occurred. SocketException (SocketException: OS Error: No route to host, errno = 8) |
As above, we still need a reproduction case that we can debug. |
This issue is hard to spot, at least in my case, i only know it is happening when i see the crashlytics dashboard. Crashlytics report
My code@protected
Future<Map<String, dynamic>> getData(Uri url) async {
http.Response result;
final httpClientInstance = new httpClient.IOClient();
try {
result = await httpClientInstance.get(url, headers: this._getHeaders());
} catch (ex, s) {
// process error
} finally {
httpClientInstance.close();
}
if (await _processResponseForTokenRefreshment(result)) {
return getData(url);
}
return this._processResponse(result);
} |
I came across the same issue today. It seems to be an error thrown inside the http package itself outside of the async/await context, so it cannot be handled by try-catch.. Looks like the issue is thrown in var ioRequest = (await _inner!.openUrl(request.method, request.url)) Any progress on this? Code to reproduce: #508 (comment) |
Any progress here? |
Also having this issue. This bug is cluttering log outputs. |
I had the same issue, I'm not sure if my catch was only catching http errors but when I changed my to try{ it seems to work |
See this issue We need to use the onError callback as well.
Also, I programatically close the socket
If I omit the onError, I get uncaught SocketExceptions. Soo.... No clue what's going on here |
Calling the error throwing function inside runZonedGuarded helped me catch the error. |
Now good luck with |
In my case, removing the timeout duration specification seems to have fixed the error. I changed somthing like this:
into somenthing like this:
|
I'm also experiencing this issue. I'm sending multiple get requests, and it seems to me that with a timeout shorter than this packages internal timout you will run into this issue. Probably because the code execution has moved on already and the catch statement is no longer actively looking for something to catch. EDIT: to clarify, this is indeed not a bug in http package, but a bug in Dart and Futures. Or my and others limited knowledge of Futures and not knowing how to correctly handle this behaviour. Here is a minimal reproducable example: Future<void> main() async {
try {
var resultFuture = complexAsyncTask();
var timeoutFuture = resultFuture.timeout(const Duration(seconds: 1), onTimeout: () {
print("timeout");
return "timeout return";
});
final String result = await timeoutFuture;
print(result);
} catch (e) {
print("catched exception: $e");
}
}
Future<String> complexAsyncTask() => _withTryFinallyAwait(() => _complexAsyncTask());
Future<T> _withTryFinallyAwait<T>(Future<T> Function() fn) async {
try {
return await fn();
} finally {
print("finally");
}
}
Future<String> _complexAsyncTask() async {
return await Future.delayed(const Duration(seconds: 2), () {
throw Exception('exception thrown after 2 seconds delay');
//return "success";
});
} If we await resultFuture (like in the example code), we have to wait for 2 seconds and the exception will be catched correctly. Anybody knows how to wait only for the timeout but still catch an exception thrown in the async task ? |
Any update here? |
+1 |
Hi, I got the same error and I fixed it by using runZonedGuarded here's my code Future<Response?> post(String path, dynamic parameter) async =>
runZonedGuarded<Future<Response?>>(() async {
return await client.post(path,
data: json.encode(parameter),
options: Options(
headers: headers
..addAll(<String, String>{
'Authorization': await localData.read(accessTokenName) ?? ''
}),
));
}, (error, stack) {
throw Exception('SERVER DOWN');
}); https://api.flutter.dev/flutter/dart-async/runZonedGuarded.html for more explanation |
BLESS YOU!!! @bkan36 |
thanks @CrownedComedian. At the moment I gave up and will continue to develop other features.... |
My situation is a bit different then that mentioned in this thread -- I was lucky to have even stumbled upon it. I've been working on an app to run provisioning code for my ESP device. Using Flutter's http package to communicate to the device abruptly ended my connection for some unknown reason, so I'm using platform specific code which seems to handle things. The exception I was getting was:
Then my platform code has the normal .setMethodCallHandler() with a switch statement in it that will run a call to my ESP device on a background thread via a Handler with a listener that will return .success() or .error() as usual. The SocketException was not being caught (even though other exceptions were) until I added your suggested code. Not sure if that answers your question, but maybe something you can try. Hope it helps! @bkan36 |
I'm trying to build an iOS app with Flutter, but I keep getting this error: Unhandled Exception: ClientException with SocketException: Connection failed (OS Error: No route to host, errno = 65), address = t*********.com, port = 443. Does anyone know how to fix this? I'm using the latest version of Flutter and Xcode. Thanks in advance. |
Is their a solution for this issue? Or some way to avoid that the app freeze and stops working? If I turn Off(on purpose) my server and try a simple get request with a Timeout Duration (AS mentioned by @Sajonji ) the Clientexception will be thrown and the app will stop to Work. An easy to reproduce case:
When running the snippet with wait errorShowCase(true); the Log output looks as follow:
However if now you let the App run without doing anything you will get the error (Note it can take up to 5 Minutes until this happens): Ausnahme aufgetreten. From the package io_client.dart (line 119):
If however you call the method like this await errorShowCase(false); the output will be
Again we need to wait almost 5 Minutes:
However here the exception was caught and the app is still working. I tried all the fix attempts mentioned above (like using onError as mentioned by @flo80 ) however none of them is working. As @Sajonji mentioned the issue is only arising when we specify our own timeout. A workaround (probably one of the worst but a possibility) is to omit the timeout part in the http call. |
I'm having the same issue with the mailer package. If the connection port is incorrect then a uncatchable SocketException is thrown. So I suspect that the bug is not specifically an issue with the http package but rather the the Socket class in dart:io - for clarity I'm actually using the SecureSocket class but I suspect the problem is universal. Here is the code in question: import 'dart:io';
import 'package:logging/logging.dart';
import 'package:mailer/mailer.dart' as mailer show send;
import 'package:mailer/mailer.dart' hide send;
import 'package:mailer/smtp_server.dart';
import 'smtp_settings.dart';
import 'util/exceptions.dart';
class SmtpClient {
factory SmtpClient() {
if (_self == null) {
throw StateError(
'''You must initialise the SmtpClient. Call SmtpClient.fromArgs()''');
}
return _self!;
}
SmtpClient.fromArgs(
{required this.host,
required this.port,
required this.useAuth,
required this.useTLS,
this.authUser,
this.authPassword}) {
smtpServer = SmtpServer(host,
port: port,
allowInsecure: !useTLS,
username: authUser,
password: authPassword);
}
static final logger = Logger('smtp');
late final SmtpServer smtpServer;
final String host;
final int port;
final bool useAuth;
final bool useTLS;
final String? authUser;
final String? authPassword;
static SmtpClient? _self;
static const hostKey = 'smtp_host';
static const portKey = 'smtp_port';
/// Send an email
/// Throws [SMTPException] if the send fails.
Future<SendReport> send(
{required EmailAddress from,
required List<EmailAddress> to,
required String subject,
required String body,
String? html,
List<EmailAddress> cc = const [],
List<EmailAddress> bcc = const []}) async {
final message = Message()
..from = Address(from)
..recipients.addAll(to.map<Address>(Address.new))
..ccRecipients.addAll(cc.map<Address>(Address.new))
..bccRecipients.addAll(bcc.map<Address>(Address.new))
..subject = subject
..text = body;
if (html != null) {
message.html = html;
}
try {
return mailer.send(message, smtpServer);
} on SocketException catch (e) {
/// fails to catch the Socket Exception
throw SMTPException.withCause(e.toString(), e);
} on Exception catch (e) {
throw SMTPException.withCause(e.toString(), e);
}
}
}
typedef EmailAddress = String;
|
Flutter App crashed after getting this exception
Exception has occurred.
SocketException (SocketException: OS Error: No route to host, errno = 113, address = 10.162.18.32, port = 60208)
THE same URL is accessible from the testing phone, Postman.
also tried with
Still, Exception is not handled.
flutter doctor
Screenshots
https://i.ibb.co/VVHV3Sr/image.png
https://i.ibb.co/GMRZZ21/image.png
The text was updated successfully, but these errors were encountered: