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
In Flutter, the
http
package does throw aClientException
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:
The case that you described
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.
If you want to disable CORS in Flutter Web, you can achieve it by running your project with the following command:
As for the rest of the case, the response.statusCode should be sufficient.