Sub topic 7
Handling HTTP errors and failed connections
This chapter assumes you can write async Dart, make a GET request with the http package, and decode JSON into a model class. Those steps were covered in the earlier chapters on GET requests and JSON models. Here the focus is on what happens when the request does not go as planned.
Why errors need their own design
A network call can fail in several different ways, and each one reaches your code differently.
- The server answers, but with a status code outside the 2xx range, such as 404 or 500. The
httppackage does not throw for these. You get a normalResponseobject. - The server never answers in time. Your code waits until a timeout fires.
- The connection fails before any answer arrives. The device is offline, DNS lookup fails, or the server refuses the connection.
- The server answers with 200 but the body is not what you expected, for example HTML instead of JSON.
If you handle only the happy path, the first case silently produces a model built from an error body. The other cases crash with exceptions the user cannot understand. The goal is to turn all of these into one exception type that the UI can show.
The four failure categories
| Failure | What you observe | How it shows up in Dart |
|---|---|---|
| Error status (4xx, 5xx) | A `Response` with `statusCode` outside 200 to 299 | No exception. You must check the status. |
| Timeout | No response within your limit | `TimeoutException` from `dart:async` |
| Connection failure | No usable connection | `http.ClientException`, or `SocketException` on `dart:io` platforms |
| Bad body | A 2xx response with unexpected content | `FormatException` from `jsonDecode`, or `TypeError` from a bad cast |
Knowing this table is most of the skill. The rest is writing code that sorts each failure into a clear category.
Reading status codes
Status codes come in classes. The first digit tells you who is at fault and whether a retry could help.
| Range | Meaning | Typical examples | Retry helps? |
|---|---|---|---|
| 2xx | Success | 200 OK, 201 Created, 204 No Content | Not needed |
| 3xx | Redirect | 301, 304 | The client usually follows these automatically |
| 4xx | Client error | 400, 401, 403, 404, 422, 429 | Usually no, except 408 and 429 |
| 5xx | Server error | 500, 502, 503, 504 | Sometimes, if the failure is temporary |
A few codes deserve special handling in an app:
- 401 Unauthorized usually means the token is missing or expired. The app may need to sign the user in again.
- 403 Forbidden means you are identified but not allowed.
- 404 Not Found means the resource does not exist. For a list screen this may be an empty state rather than an error.
- 422 Unprocessable Entity often carries validation messages in the body.
- 429 Too Many Requests means you are being rate limited. A
Retry-Afterheader may say how long to wait.
Do not test for == 200 everywhere. A successful POST returns 201, and a successful DELETE often returns 204 with an empty body. Check for the 2xx range unless you need a specific code.
One exception type for the app
Scattering try/catch blocks over every screen leads to inconsistent messages. Define a single exception class and convert every failure into it at the edge of your networking code.
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).timeout(const Duration(seconds: 10));
if (response.statusCode >= 200 && response.statusCode < 300) {
return response;
}
throw ApiException('Request failed', statusCode: response.statusCode);
} on TimeoutException {
throw const ApiException('The request timed out');
} on http.ClientException catch (e) {
throw ApiException('Connection problem: ${e.message}');
}
}Walk through what this does:
client.get(uri)starts the request, and.timeout(...)limits how long you wait for the response.- A 2xx status returns the response to the caller.
- Any other status throws an
ApiExceptionthat carries the status code. - A
TimeoutExceptionis caught and rethrown as anApiExceptionwith a readable message. - An
http.ClientExceptioncovers connection problems and is converted the same way.
Notice that the ApiException thrown for a bad status is thrown inside the try block. The two on clauses do not match ApiException, so it passes through unchanged. That is the intended behavior.
Where SocketException fits
On mobile and desktop, a failed connection may surface as SocketException from dart:io. The http package's IOClient usually wraps it in http.ClientException, which is why catching http.ClientException is enough in most cases. On the web, the browser reports failures through XMLHttpRequest or fetch, and the package also reports them as ClientException. The browser hides the reason. A blocked cross-origin request (CORS) and a dead server look the same to your code.
Importing dart:io breaks web builds, so avoid catching SocketException in shared code. Catching http.ClientException keeps the code portable.
Failures after a successful status
A 200 response does not guarantee a usable body. jsonDecode throws FormatException for invalid JSON. A cast such as as Map<String, dynamic> throws TypeError if the shape is different, for example when the server returns a list. A missing key gives null, and json['id'] as int then fails with a TypeError.
Wrap parsing in the same conversion so the UI never sees these raw errors:
import 'dart:convert';
import 'package:http/http.dart' as http;
class Post {
const Post({required this.id, required this.title});
factory Post.fromJson(Map<String, dynamic> json) =>
Post(id: json['id'] as int, title: json['title'] as String);
final int id;
final String title;
}
class ApiException implements Exception {
const ApiException(this.message, {this.statusCode});
final String message;
final int? statusCode;
@override
String toString() => 'ApiException($statusCode): $message';
}
Post parsePost(http.Response response) {
try {
final decoded = jsonDecode(response.body);
return Post.fromJson(decoded as Map<String, dynamic>);
} on FormatException {
throw const ApiException('The server sent invalid JSON');
} on TypeError {
throw const ApiException('The server sent an unexpected response shape');
}
}Catching TypeError is unusual in Dart, because it is an Error and not an Exception. Here it is justified: the data comes from outside your program and you are validating it at a trust boundary. Inside your own code, you would fix the bug instead of catching the error.
Reading error bodies
Many APIs explain a failure in the response body, often as JSON such as {"message": "Title is required"}. Use it when it exists, but never assume it does. A gateway can return an HTML page for a 502.
import 'dart:convert';
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';
}
String _messageFrom(http.Response response) {
try {
final body = jsonDecode(response.body);
if (body is Map<String, dynamic> && body['message'] is String) {
return body['message'] as String;
}
} on FormatException {
// The body is not JSON. Fall through to the default message.
}
return 'Request failed';
}
http.Response ensureSuccess(http.Response response) {
if (response.statusCode >= 200 && response.statusCode < 300) {
return response;
}
throw ApiException(
_messageFrom(response),
statusCode: response.statusCode,
);
}The is check guards the shape, so no cast can fail. An empty or non-JSON body falls back to a default message. Server messages are meant for developers as often as for users, so decide whether to display them or to map status codes to your own wording.
Mapping errors to user messages
The exception carries facts. The UI decides how to phrase them. Keep this mapping in one place:
class ApiException implements Exception {
const ApiException(this.message, {this.statusCode});
final String message;
final int? statusCode;
}
String userMessage(Object error) {
if (error is ApiException) {
switch (error.statusCode) {
case 401:
return 'Please sign in again.';
case 403:
return 'You do not have access to this.';
case 404:
return 'We could not find that.';
case 429:
return 'Too many requests. Try again shortly.';
case final code? when code >= 500:
return 'The server had a problem. Try again later.';
default:
return error.message;
}
}
return 'Something went wrong.';
}The case final code? when code >= 500 line uses a Dart 3 pattern. It matches a non-null status and binds it to code. A timeout has no status code, so it falls to the default branch and shows its own message.
The flow of a request
Every failure ends at the same place. The calling code needs only one catch.
Common mistakes
- Treating a non-200 status as success. Decoding a 404 error body as a model usually crashes with a confusing cast error. Check the status first.
- Requiring exactly 200. This rejects valid 201 and 204 responses.
- Catching
Exceptioneverywhere. A broadcatch (e)hides programming mistakes. Catch specific types, and let unexpected ones surface. - Swallowing errors. An empty
catchblock leaves the UI in a permanent loading state. - Showing raw exception text. Strings like
SocketException: Failed host lookupmean nothing to users. - Using
contextafter anawait. If you show a message after a failed request, checkmountedfirst, because the widget may have left the tree. - Forgetting that
.timeoutdoes not cancel. The request may still complete in the background.
Testing the error paths
Error handling is easy to break and rarely exercised by hand. MockClient lets you simulate each failure. A later chapter covers it fully, but this short test shows the idea.
import 'package:flutter_test/flutter_test.dart';
import 'package:http/http.dart' as http;
import 'package:http/testing.dart';
class ApiException implements Exception {
const ApiException(this.message, {this.statusCode});
final String message;
final int? statusCode;
}
Future<http.Response> getChecked(http.Client client, Uri uri) async {
final response = await client.get(uri);
if (response.statusCode >= 200 && response.statusCode < 300) {
return response;
}
throw ApiException('Request failed', statusCode: response.statusCode);
}
void main() {
test('a 404 becomes an ApiException with the status code', () async {
final client = MockClient((request) async => http.Response('', 404));
expect(
() => getChecked(client, Uri.https('example.com', '/missing')),
throwsA(
isA<ApiException>().having((e) => e.statusCode, 'statusCode', 404),
),
);
});
}Summary
- A non-2xx status is not an exception in
http. Check it yourself. - Convert timeouts, connection failures, bad statuses and bad bodies into one exception type.
- Check for the 2xx range, not for 200 alone.
- Catch
http.ClientExceptioninstead ofSocketExceptionto stay web compatible. - Keep the mapping from exception to user message in one function.
Exercise
A DELETE request succeeds and the server returns status 204 with an empty body. Your helper throws ApiException for any status other than 200. What goes wrong, and how do you fix it?
Show answer
The helper rejects a valid response, so the user sees an error although the item was deleted. Change the check to accept the whole 2xx range (statusCode >= 200 && statusCode < 300). Also avoid calling jsonDecode on the empty body of a 204 response.
Exercise
Why does the getChecked function not need an extra on ApiException clause, even though it throws ApiException inside the try block?
Show answer
The on clauses only match TimeoutException and http.ClientException. An ApiException matches neither, so it is not caught and propagates to the caller unchanged.
Exercise
A server returns status 200 with an HTML error page instead of JSON. Which exception does jsonDecode throw, and where should you convert it?
Show answer
jsonDecode throws a FormatException. Convert it to an ApiException in the parsing step, next to the jsonDecode call, so the UI only has to handle one exception type.