diff --git a/CHANGELOG.md b/CHANGELOG.md index 0816057..edf8afe 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Added - Filtering support for collections ([#97](https://github.com/f3ath/json-api-dart/pull/97)) +### Changed +- The client will not attempt to decode the body of the HTTP response with error status if the correct Content-Type +is missing. Before in such cases a `FormatException` would be thrown. + ## [4.1.0] - 2020-05-28 ### Changed - `DartHttp` now defaults to utf8 if no encoding is specified in the response. diff --git a/lib/src/client/json_api_client.dart b/lib/src/client/json_api_client.dart index e1048ec..f59269c 100644 --- a/lib/src/client/json_api_client.dart +++ b/lib/src/client/json_api_client.dart @@ -181,10 +181,14 @@ class JsonApiClient { Future> _call( HttpRequest request, D Function(Object _) decodePrimaryData) async { final response = await _httpHandler(request); - final document = response.body.isEmpty ? null : jsonDecode(response.body); - if (document == null) { + final status = StatusCode(response.statusCode); + if (response.body.isEmpty || + (status.isFailed && + response.headers['content-type']?.contains(Document.contentType) != + true)) { return Response(response.statusCode, response.headers); } + final document = response.body.isEmpty ? null : jsonDecode(response.body); if (StatusCode(response.statusCode).isPending) { return Response(response.statusCode, response.headers, asyncDocument: document == null diff --git a/test/unit/client/non_json_response_test.dart b/test/unit/client/non_json_response_test.dart new file mode 100644 index 0000000..15d7896 --- /dev/null +++ b/test/unit/client/non_json_response_test.dart @@ -0,0 +1,23 @@ +import 'package:json_api/client.dart'; +import 'package:json_api/http.dart'; +import 'package:json_api/routing.dart'; +import 'package:test/test.dart'; + +import '../../helper/test_http_handler.dart'; + +void main() { + final handler = TestHttpHandler(); + final client = RoutingClient(JsonApiClient(handler), StandardRouting()); + test('Error status code with incorrect content-type is not decoded', + () async { + handler.nextResponse = HttpResponse(500, body: 'Something went wrong'); + + final r = await client.fetchCollection('books'); + expect(r.isAsync, false); + expect(r.isSuccessful, false); + expect(r.isFailed, true); + expect(r.data, isNull); + expect(r.asyncData, isNull); + expect(r.statusCode, 500); + }); +}