findError static method

ServiceErrorResponse findError({
  1. Object? object,
  2. required int statusCode,
  3. List<int>? allowStatusCode,
})

Finds an error message from the response based on the status code and object type.

If the status code is 401 or 403 and the object is a list of bytes or a string, it attempts to decode the error message. Returns: A decoded error message if applicable, otherwise null.

Implementation

static ServiceErrorResponse findError({
  Object? object,
  required int statusCode,
  List<int>? allowStatusCode,
}) {
  bool isValidStatusCode() {
    return (allowStatusCode?.contains(statusCode) ?? false);
  }

  String? error = () {
    try {
      return JsonParser.valueAsString(
        ecodeResponse(body: object, encoding: ServiceReponseEncoding.string),
      );
    } catch (_) {
      return null;
    }
  }();
  final htmlReg = RegExp(
    r'<(html|head|body|title|h1|h2|h3|h4|h5|h6|p|div|span|a|form|table|img)[^>]*>',
    caseSensitive: false,
  );
  if (error != null && (htmlReg.hasMatch(error) || error.isEmpty)) {
    error = null;
  }

  return ServiceErrorResponse(
    statusCode: statusCode,
    error: error,
    validate: isValidStatusCode(),
    jsonError: error == null ? null : StringUtils.tryToJson(error),
  );
}