0

I use a function for an http get request and with the correct URL it works fine.

However, if I change the URL to a wrong one (to simulate some change in a third party backend) I always get an exception in the json.decode line: Unhandled exception: Socket Exception: Failed host lookup. 'myurl.com' (OS Error: No address associated with hostname, errno = 7)

Why does my try/catch block not catch this exception? How can I catch the exception if the status code is 200 but not I get a SocketException?

  varLookup(String variable) async {
    http.Response response = await http.get('https://myurl.com/${variable}');
    if (response.statusCode == 200) {
      try {
        var jsonResponse = json.decode(response.body);
        return;
      } catch (error) {
        var getError = error;
        return;
      }
    } else {
      print('Status code not 200');
      return;
    }
  }
Heikkisorsa
  • 740
  • 9
  • 31
  • 1
    Does this answer your question? [How do I check Internet Connectivity using HTTP requests(Flutter/Dart)?](https://stackoverflow.com/questions/61036643/how-do-i-check-internet-connectivity-using-http-requestsflutter-dart). I've covered both socket and timeout exceptions in that one. As to why, please look closely where the try block begins (before the await). – Uroš Aug 10 '20 at 14:11
  • @Uroš Yes, this answers the question. Thank you! – Heikkisorsa Aug 10 '20 at 14:16

0 Answers0