skip to Main Content

Flutter web http throws a http.ClientException on a response with status other than 200. The exception has a message "XMLHttpRequest error". How do I get the actual response body and statusCode? Examples online say use response.statusCode but exception is thrown before response is returned. Flutter newbie so surely missing something silly..

try {
   Uri uri = Uri.parse(apiEndpoint);
   final response = await http.get(uri, headers: {"Authorization": "Bearer token"});
   print(response.statusCode); // never happens if status is not 200
} catch(e) {
   print(e); // Was it 403, 404 or 500???
}

2

Answers


  1. In Flutter, the http package does throw a ClientException when a network error occurs, but it does not throw this exception for HTTP status codes other than 200 by default. Instead, it returns the response with the non-200 status code along with the response body. You can access the status code and response body directly without the need for exception handling.

    Here is the modified code:

    try {
      Uri uri = Uri.parse(apiEndpoint);
      final response = await http.get(uri, headers: {"Authorization": "Bearer token"});
    
      // Check if the response status code is not 200 (OK)
      if (response.statusCode != 200) {
        print('Status Code: ${response.statusCode}');
        print('Response Body: ${response.body}');
      } else {
        // Handle the successful response here
        print('Successful Response: ${response.statusCode}');
      }
    } catch (e) {
      print('Error: $e');
    }
    
    Login or Signup to reply.
  2. The case that you described

    XMLHttpRequest error

    occurs because of the CORS, which throws an Exception rather than returning the result.

    So to catch that, you can look at the sample code below.

    try {
      Uri uri = Uri.parse(apiEndpoint);
      final response =
          await http.get(uri, headers: {"Authorization": "Bearer token"});
      debugPrint("ResponseCode: ${response.statusCode}");
    } catch (e) {
      if (e is http.ClientException && e.message == "XMLHttpRequest error.") {
        debugPrint("CORS error.");
        return;
      }
      debugPrint("Exception: ${e.toString()}");
    }
    

    If you want to disable CORS in Flutter Web, you can achieve it by running your project with the following command:

    flutter run -d chrome –web-browser-flag "–disable-web-security"

    As for the rest of the case, the response.statusCode should be sufficient.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search