handleResponse method

  1. @override
String? handleResponse(
  1. Response res
)
override

Returns an error message if the response indicates failure, null otherwise.

Implementation

@override
String? handleResponse(http.Response res) {
  try {
    final responseBody = utf8.decode(res.bodyBytes);

    if (responseBody.trim().isEmpty) {
      if (res.statusCode >= 200 && res.statusCode < 300) return null;
      return 'Server returned an empty response';
    }

    if (isHtmlOrTextResponse(responseBody)) {
      return 'The server returned an invalid response. Please try again later.';
    }

    try {
      final Map<String, dynamic> response = jsonDecode(responseBody);
      if (res.statusCode >= 200 && res.statusCode < 300) return null;
      final String errorMessage = getErrorMessage(response['message']);
      return errorMessage.isNotEmpty
          ? errorMessage
          : 'An unexpected error occurred.';
    } on FormatException {
      if (res.statusCode >= 200 && res.statusCode < 300) return null;
      return 'Failed to parse the response. Please try again later.';
    }
  } catch (e) {
    return 'Failed to process the response. Please check your connection and try again.';
  }
}