Sub topic 7
Handling HTTP errors and failed connections
This chapter assumes you know Dart classes, null safety, Future, async and await, and the basic http package. You should also know how to call a function from a Flutter widget.
A REST request can fail in two different ways:
- The server receives the request and returns an HTTP error status.
- The request cannot complete because of a timeout, lost connection, invalid URL, or another client problem.
Your app should handle both cases. A network error is not the same as a 404 Not Found, and the UI may need to show different messages.
Check the HTTP status
The http package returns a response even when the server sends a status such as 400 or 500. It does not automatically throw for every non-success status.
| Status range | Meaning | Typical app action |
|---|---|---|
| 200–299 | The request succeeded | Decode and use the body |
| 400–499 | The request or credentials are invalid | Show a user or authentication message |
| 500–599 | The server failed | Show a temporary failure message |
A successful response has a status from 200 through 299. Check this range before decoding the body.
import 'dart:async';
import 'package:http/http.dart' as http;
class ApiException implements Exception {
const ApiException(this.message, {this.statusCode});
final String message;
final int? statusCode;
@override
String toString() => 'ApiException($statusCode): $message';
}
Future<http.Response> getChecked(
http.Client client,
Uri uri,
) async {
try {
final response = await client
.get(uri, headers: {'Accept': 'application/json'})
.timeout(const Duration(seconds: 10));
if (response.statusCode >= 200 && response.statusCode < 300) {
return response;
}
throw ApiException(
'The server returned an error.',
statusCode: response.statusCode,
);
} on TimeoutException {
throw const ApiException('The request took too long.');
} on http.ClientException catch (error) {
throw ApiException('Connection problem: ${error.message}');
}
}ApiException gives the rest of your app one predictable error type. The optional statusCode lets the UI or API client react to a specific status.
Separate failures in the UI
Catch ApiException around the API call. Use the status code for decisions, but avoid showing raw technical details to users.
Future<void> loadPost(http.Client client) async {
final uri = Uri.https('jsonplaceholder.typicode.com', '/posts/1');
try {
final response = await getChecked(client, uri);
print('Received ${response.body}');
} on ApiException catch (error) {
if (error.statusCode == 401) {
print('Please sign in again.');
} else if (error.statusCode == 404) {
print('That post does not exist.');
} else {
print(error.message);
}
}
}JSON decoding can fail even after a successful status. A server might return malformed JSON or a different shape than expected. Treat decoding as another failure boundary and convert it to an application-level error when appropriate.
Decide when to retry
Retrying can help with a temporary connection failure or a server 503 response. It cannot fix a bad request, invalid credentials, or a missing resource.
Retry only operations that are safe to repeat. A repeated GET is usually safe. Automatically repeating a POST can create duplicate records unless the API supports idempotency keys.
Exercise
Why should a client check response.statusCode before decoding a response body?
Show answer
Because the server can return an error status with an error body, and decoding it as the expected success model can hide the real failure or throw a misleading parsing error.