2

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());
    }
  • What package are you using? – Denzel Apr 21 '22 at 09:16
  • `catchError` should be catching the exception, but you rethrow it. The rethrown exception will not be caught by the outer `catch` block because exception is asynchronous, and since you're not using `await`, that outer `catch` block can catch only synchronous exceptions. – jamesdlin Apr 21 '22 at 15:07

1 Answers1

2

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.

DEFL
  • 907
  • 7
  • 20