interceptResponse<T> method

Future<T> interceptResponse<T>({
  1. required String method,
  2. required String url,
  3. dynamic body,
  4. Map<String, String>? headers,
})

Intercept an HTTP response

Implementation

Future<T> interceptResponse<T>({
  required String method,
  required String url,
  dynamic body,
  Map<String, String>? headers,
}) async {
  if (!NetworkInterceptor.isEnabled) {
    return await this as Future<T>;
  }

  final requestId = NetworkInterceptor.captureRequest(
    method: method,
    url: url,
    headers: headers ?? {},
    body: body,
  );

  try {
    final response = await this;

    // Try to extract response data if it's an http.Response
    dynamic responseBody;
    Map<String, String> responseHeaders = {};
    int? statusCode;

    // Use dynamic to check if response has statusCode, headers, body
    try {
      final dynamic resp = response;
      if (resp != null) {
        // Try to access common http.Response properties
        try {
          statusCode = resp.statusCode as int?;
        } catch (_) {}

        try {
          responseBody = resp.body;
        } catch (_) {}

        try {
          final headers = resp.headers;
          if (headers is Map) {
            responseHeaders = headers.map((key, value) =>
              MapEntry(key.toString(), value.toString()));
          }
        } catch (_) {}
      }
    } catch (_) {
      // If we can't extract, just use the response as string
      responseBody = response.toString();
    }

    NetworkInterceptor.captureResponse(
      requestId: requestId,
      statusCode: statusCode,
      headers: responseHeaders,
      body: responseBody,
    );

    return response as T;
  } catch (e, stackTrace) {
    NetworkInterceptor.captureResponse(
      requestId: requestId,
      statusCode: null,
      headers: {},
      body: {'error': e.toString(), 'stackTrace': stackTrace.toString()},
    );
    rethrow;
  }
}