throwOnError method

Future<void> throwOnError()

Throws an ApiRequestException if the status code is greater or equal to 400.

If this method throws, bodyData can not be accessed anymore because the stream is drained to parse exception data. Body data can be accessed via the ApiRequestException that is thrown.

This method is called by RestClient by default before returning the response. This can be disabled by setting the throwOnError argument on request methods to false.

Also throwOnError will drain the stream to parse error data in the case of a non-success status code.

Implementation

Future<void> throwOnError() async {
  if (statusCode >= 400) {
    if (headers['content-type']?.contains(Mime.json) ?? false) {
      try {
        final textBody = await getTextBody();
        try {
          final jsonBody = jsonDecode(textBody) as Map<String, dynamic>;
          throw ApiRequestException.fromResponse(
            statusCode,
            {
              'statusCode': statusCode,
              ...jsonBody,
            },
          );
        } on ApiRequestException catch (_) {
          rethrow;
        } catch (_) {
          throw ApiRequestException.fromResponse(statusCode, {
            'statusCode': statusCode,
            'errorBody': textBody,
          });
        }
      } on ApiRequestException catch (_) {
        rethrow;
      } catch (e) {
        throw ApiRequestException.fromResponse(
          statusCode,
          {
            'statusCode': statusCode,
            'clientError': 'Could not parse error response.',
            'clientErrorDetails': e.toString(),
          },
        );
      }
    } else if (headers['content-type']?.contains(Mime.plainText) ?? false) {
      // Create exception data that are similar to datahub error responses for
      // servers that are not providing json error data.
      try {
        throw ApiRequestException.fromResponse(
          statusCode,
          {
            'statusCode': statusCode,
            'errorMessage': await getTextBody(),
          },
        );
      } catch (e) {
        throw ApiRequestException.fromResponse(
          statusCode,
          {
            'statusCode': statusCode,
            'clientError': 'Could not parse error response.',
            'clientErrorDetails': e.toString(),
          },
        );
      }
    }

    throw ApiRequestException.fromResponse(statusCode, {});
  }
}