handleStatusCode method

  1. @alwaysThrows
void handleStatusCode(
  1. Response response
)

Internal method to handle status codes

Implementation

@alwaysThrows
void handleStatusCode(http.Response response) {
  String? message;
  List<Map<String, String>>? errors;
  if (response.headers['content-type']!.contains('application/json')) {
    final json = jsonDecode(response.body);
    message = json['message'];
    if (json['errors'] != null) {
      try {
        errors = List<Map<String, String>>.from(json['errors']);
      } catch (_) {
        errors = [
          {'code': json['errors'].toString()}
        ];
      }
    }
  }
  switch (response.statusCode) {
    case 404:
      throw NotFound(this, 'Requested Resource was Not Found');
    case 401:
      throw AccessForbidden(this);
    case 400:
      if (message == 'Problems parsing JSON') {
        throw InvalidJSON(this, message);
      } else if (message == 'Body should be a JSON Hash') {
        throw InvalidJSON(this, message);
      } else {
        throw BadRequest(this);
      }
    case 422:
      final buff = StringBuffer();
      buff.writeln();
      buff.writeln('  Message: $message');
      if (errors != null) {
        buff.writeln('  Errors:');
        for (final error in errors) {
          final resource = error['resource'];
          final field = error['field'];
          final code = error['code'];
          buff
            ..writeln('    Resource: $resource')
            ..writeln('    Field $field')
            ..write('    Code: $code');
        }
      }
      throw ValidationFailed(this, buff.toString());
    case 500:
    case 502:
    case 504:
      throw ServerError(this, response.statusCode, message);
  }
  throw UnknownError(this, message);
}