throwException function

void throwException(
  1. StreamedResponse rs,
  2. String body,
  3. Map<String, AwsExceptionFn> exceptionFnMap
)

Implementation

void throwException(StreamedResponse rs, String body,
    Map<String, AwsExceptionFn> exceptionFnMap) {
  var type =
      rs.headers['x-amzn-errortype']?.split(':').firstOrNull ?? 'UnknownError';
  String? message;

  final statusCode = rs.statusCode.toString();

  if (body.isNotEmpty == true) {
    try {
      final e = jsonDecode(body);
      if (e['__type'] != null || e['code'] != null) {
        type = ((e['__type'] as String?) ?? (e['code'] as String?))!
            .split('#')
            .last;
      }
      if (type == 'RequestEntityTooLarge') {
        message = 'Request body must be less than 1 MB';
      } else {
        message = e['message'] as String? ?? e['Message'] as String?;
      }
    } catch (_) {
      message = statusCode;
    }
  } else {
    message = statusCode;
  }

  final fn = exceptionFnMap[type];
  final exception = fn != null
      ? fn(type, message ?? '')
      : GenericAwsException(
          type: type,
          code: statusCode,
          message: message,
        );
  throw exception;
}