Skip to content

Instantly share code, notes, and snippets.

@nemethmik
Created August 4, 2019 18:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nemethmik/ed3eec698ae9afb1c08a6fafe240a56a to your computer and use it in GitHub Desktop.
Save nemethmik/ed3eec698ae9afb1c08a6fafe240a56a to your computer and use it in GitHub Desktop.
When timeout is raised on HttpClient because of IP address issues, NoSuchMethodEror is thrown instead of SocketException
import 'dart:io';
import 'package:test/test.dart';
void main() {
test("Login with HTTPClient",() async {
try {
//final String queryUrl = "http://google.com"; //OK
// final String queryUrl = "http://googleKRIXKRAKSZ.com"; //SocketException is OK
//
// NoSuchMethodError: The method 'setOption' was called on null.
// Receiver: null
// Tried calling: setOption(Instance of 'SocketOption', true)
final String queryUrl = "http://192.168.250.92:50001"; //Just use any nonresponding/invalid IP address
final HttpClient client = HttpClient()..connectionTimeout = Duration(seconds: 5);
//When the timeout duration it works great, we receive a SocketException: OS Error: Operation timed out
//final HttpClient client = HttpClient()..connectionTimeout = Duration(minutes: 2);
final HttpClientRequest request = await client.getUrl(Uri.parse(queryUrl));
final HttpClientResponse response = await request.close();
expect(response, isNotNull);
expect(response.statusCode,200);
} on SocketException catch(error) {
print(error);
expect(error is SocketException,isTrue);
} on NoSuchMethodError catch(error,stackTrace) {
print(error);
print(stackTrace);
expect(error is NoSuchMethodError,isFalse);
} catch(error,stackTrace) {
print("Huh, unexpected type of error");
print(error);
print(stackTrace);
expect(error,isNull);
}
},timeout: Timeout(Duration(minutes: 3)));
}
@nemethmik
Copy link
Author

nemethmik commented Aug 4, 2019

This is a Dart test script to demonstrate the issue with the timeout exception of HttpClient.
This issue happens when the IP address is not valid, or the port is not listening. Normally, within 30 seconds or so a nice SocketException is thrown, but when we don't want to wait that long we set the timeout on the HTTP client of dart:io. Instead of the SocketException we have a NoSuchMethodError.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment