Skip to content

Commit b9af0ac

Browse files
authored
Invalid content type (#98)
1 parent 94902a4 commit b9af0ac

File tree

3 files changed

+33
-2
lines changed

3 files changed

+33
-2
lines changed

CHANGELOG.md

+4
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
88
### Added
99
- Filtering support for collections ([#97](https://github.com/f3ath/json-api-dart/pull/97))
1010

11+
### Changed
12+
- The client will not attempt to decode the body of the HTTP response with error status if the correct Content-Type
13+
is missing. Before in such cases a `FormatException` would be thrown.
14+
1115
## [4.1.0] - 2020-05-28
1216
### Changed
1317
- `DartHttp` now defaults to utf8 if no encoding is specified in the response.

lib/src/client/json_api_client.dart

+6-2
Original file line numberDiff line numberDiff line change
@@ -181,10 +181,14 @@ class JsonApiClient {
181181
Future<Response<D>> _call<D extends PrimaryData>(
182182
HttpRequest request, D Function(Object _) decodePrimaryData) async {
183183
final response = await _httpHandler(request);
184-
final document = response.body.isEmpty ? null : jsonDecode(response.body);
185-
if (document == null) {
184+
final status = StatusCode(response.statusCode);
185+
if (response.body.isEmpty ||
186+
(status.isFailed &&
187+
response.headers['content-type']?.contains(Document.contentType) !=
188+
true)) {
186189
return Response(response.statusCode, response.headers);
187190
}
191+
final document = response.body.isEmpty ? null : jsonDecode(response.body);
188192
if (StatusCode(response.statusCode).isPending) {
189193
return Response(response.statusCode, response.headers,
190194
asyncDocument: document == null
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
import 'package:json_api/client.dart';
2+
import 'package:json_api/http.dart';
3+
import 'package:json_api/routing.dart';
4+
import 'package:test/test.dart';
5+
6+
import '../../helper/test_http_handler.dart';
7+
8+
void main() {
9+
final handler = TestHttpHandler();
10+
final client = RoutingClient(JsonApiClient(handler), StandardRouting());
11+
test('Error status code with incorrect content-type is not decoded',
12+
() async {
13+
handler.nextResponse = HttpResponse(500, body: 'Something went wrong');
14+
15+
final r = await client.fetchCollection('books');
16+
expect(r.isAsync, false);
17+
expect(r.isSuccessful, false);
18+
expect(r.isFailed, true);
19+
expect(r.data, isNull);
20+
expect(r.asyncData, isNull);
21+
expect(r.statusCode, 500);
22+
});
23+
}

0 commit comments

Comments
 (0)