handleResponse static method
dynamic
handleResponse(
- Response response
Implementation
static dynamic handleResponse(http.Response response) {
String body = response.body;
final status = response.statusCode;
// The whole 2xx range, not only 200: a 201 Created or 204 No Content is an
// ordinary answer, and treating either as a failure would break the SDK
// against any endpoint that starts using them.
if (status >= 200 && status < 300) {
if (body == '') return {};
try {
return json.decode(body);
} on FormatException catch (err) {
// A success status carrying something that is not JSON: a captive
// portal, or a proxy answering 200 with an HTML error page. Raw, this
// surfaced as `FormatException: Unexpected character (at character 1)`
// from inside the SDK, naming neither the status nor what arrived.
throw FetchDataException(
'The response was not JSON ($err): ${_truncate(body)}',
body: body,
status: status,
);
}
}
switch (status) {
case 400:
throw BadRequestException(body, status: status);
case 401:
throw UnauthorizedException(body, status: status);
// Split from 401 rather than sharing its type. A 403 is the database
// saying a collection's policy denies this, which the caller cannot fix by
// signing in again - and treating it as an expired session sent users to a
// login screen for an operation they were never permitted to perform.
case 403:
throw ForbiddenException(body, status: status);
case 404:
throw NotFoundException(body, status: status);
// The row changed between the policy check and the conditional write. The
// request was fine and can be retried once the caller has re-read it, so
// this must not fall through to FetchDataException and be announced as an
// internal server error.
case 409:
throw ConflictException(body, status: status);
case 429:
throw RateLimitedException(body, status: status);
default:
// `body` stays the response exactly as it arrived. The status is a field
// now rather than something appended to the message text.
if (body != '') {
throw FetchDataException(body, body: body, status: status);
} else {
throw FetchDataException(
'An unexpected error occurred',
status: status,
);
}
}
}