ServiceException.fromHttpResponse constructor

ServiceException.fromHttpResponse(
  1. BaseResponse response,
  2. String? responseBody
)

Create a ServiceException (or appropriate subclass) from an HTTP response.

Implementation

factory ServiceException.fromHttpResponse(
  http.BaseResponse response,
  String? responseBody,
) {
  if (responseBody == null || responseBody.isEmpty) {
    return ServiceException._fromDecodedResponse(
      'unknown error',
      response: response,
      responseBody: responseBody,
    );
  }

  final dynamic json;
  try {
    json = jsonDecode(responseBody);
  } on FormatException {
    return ServiceException._fromDecodedResponse(
      responseBody,
      response: response,
      responseBody: responseBody,
    );
  }

  final Status status;
  // The Storage Testbench sometimes returns non-conformant `Status` responses
  // with an object for the `'message'` field.
  // See https://github.com/googleapis/storage-testbench
  if (json case {'error': final Map<String, Object?> error}
      when error['code'] is int? &&
          error['message'] is String? &&
          error['details'] is List<Object?>?) {
    status = Status.fromJson(error);
  } else {
    return ServiceException._fromDecodedResponse(
      responseBody,
      response: response,
      responseBody: responseBody,
    );
  }

  return ServiceException._fromDecodedResponse(
    status.message,
    response: response,
    responseBody: responseBody,
    status: status,
  );
}