Ahmed Jihad
Ahmed Jihad

Reputation: 84

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

Upvotes: 2

Views: 1499

Answers (1)

DEFL
DEFL

Reputation: 1052

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.

Upvotes: 2

Related Questions