onError method

  1. @override
void onError(
  1. DioError err,
  2. ErrorInterceptorHandler handler
)

Called when an exception was occurred during the request.

Implementation

@override
void onError(DioError err, ErrorInterceptorHandler handler) {
  EventTracker().addEvent(getEvent(Events.RESPONSE_VALIDATION, EventTracker.sourceSdk));

  if(err.response != null) {
    var responseHeaders = err.response?.headers.map;
    var ddHeaders = (responseHeaders != null && (responseHeaders.keys.any((key) => key.toLowerCase() == 'x-dd-b') || responseHeaders.keys.any((key) => key.toLowerCase() == 'x-sf-cc-x-dd-b')));
    var code = err.response!.statusCode;
    if ((code == 401 || code == 403) && (ddHeaders)) {
      //blocked by datadome
      failedRequests.add(RetriableRequest(dio, err, handler));
      if (CaptchaPage.isDisplayed) {
        return;
      }

      if(err.response == null) {
        DataDomeLogger.error("Null DioError response info");
        return;
      }

      var captchaUrl = "";
      var response = err.response;
      switch(response!.requestOptions.responseType) {
        case ResponseType.json:
          captchaUrl = response.data['url'];
          break;
        case ResponseType.stream:
          DataDomeLogger.warning("The SDK does not support Stream ResponseType. Please change it to json.");
          break;
        case ResponseType.plain:
          try {
            var jsonObj = jsonDecode(response.data);
            captchaUrl = jsonObj['url'];
          } catch(e) {
            DataDomeLogger.error("Error decoding the response body to retrieve URL: $e");
            captchaUrl = ''; // Return an empty URL value
          }
          break;
        case ResponseType.bytes:
          try {
            final decodedJSON = jsonDecode(utf8.decode(response.data));
            captchaUrl = decodedJSON['url'];
          } catch (e) {
            DataDomeLogger.error("Error decoding the response body to retrieve URL: $e");
            captchaUrl = ''; // Return an empty URL value
          }
          break;
      }

      if(captchaUrl.trim().isEmpty) {
        DataDomeLogger.warning("Missing or empty captcha URL in response body");
        return;
      }

      if (context != null) {
        showCaptcha(
            context!,
            captchaUrl,
                (String cookie) {
              didResolveCaptcha(cookie);
            }
        );
      } else {
        Widget widget = new CaptchaPage(captchaUrl: captchaUrl,
            onCaptchaResolved: (String cookie) {
              didResolveCaptcha(cookie);
            });
        if (onCaptchaDisplay != null) {
          onCaptchaDisplay!(widget);
        }
      }
      return;
    }
  }

  super.onError(err, handler);
}