Ex code 400 when the server cannot read the spans
17692
public static HttpFailure sendErrorResponse(int code, String body) {
    return new HttpFailure(new MockResponse().setResponseCode(code).setBody(body));
  }
981559
function convertToZipkinSpan(span) {
  const result = {};
  result.traceId = utility.md5(span.traceId);
  result.parentId = span.parentSpanId;
  result.id = span.spanId;
  result.name = span.name;
  // it's microseconds
  result.timestamp = span.startTime * 1000;
  // it's microseconds
  result.duration = (span.finishTime - span.startTime) * 1000;
  result.tags = span.getTags();

  result.localEndpoint = {
    serviceName: span.getTag('appname'),
    ipv4: span.getTag('local.ipv4'),
    ipv6: span.getTag('local.ipv6'),
    port: span.getTag('local.port'),
  };

  let kind = span.getTag('span.kind');
  if (kind) {
    kind = kind.toUpperCase();
  }
  if ([ 'CLIENT', 'SERVER', 'PRODUCER', 'CONSUMER' ].includes(kind)) {
    result.kind = kind;
    result.remoteEndpoint = {
      serviceName: span.getTag('peer.service'),
      ipv6: span.getTag('peer.ipv6'),
      ipv4: span.getTag('peer.ipv4'),
      port: span.getTag('peer.port'),
    };
  }

  result.annotations = [];
  result.debug = false;
  result.shared = false;
  return result;
}
625943
def _to_spans(x):
    """"""
    if isinstance(x, Candidate):
        return [_to_span(m) for m in x]
    elif isinstance(x, Mention):
        return [x.context]
    elif isinstance(x, TemporarySpanMention):
        return [x]
    else:
        raise ValueError(f"{type(x)} is an invalid argument type")
1314682
function decode (param) {
  try {
    return decodeURIComponent(param)
  } catch (_) {
    var err = new Error('Failed to decode param "' + param + '"')
    err.status = 400
    throw err
  }
}
1105639
def interpret_span(text_spans: str) -> List[int]:
    
    m = regex.match("^(?:(?:([\(\[]\d+, \d+[\)\]])|({\d+}))[,]?\s*)+$",
                    text_spans)

    spans = m.captures(1) + m.captures(2)

    int_spans = []
    for span in spans:
        ints = list(map(int,
                        span[1: -1].split(',')))
        if span[0] == '(':
            ints[0] += 1
        if span[-1] == ']':
            ints[1] += 1
        if span.startswith('{'):
            assert(len(ints) == 1)
            ints.append(ints[0] + 1)

        assert(len(ints) == 2)

        int_spans.append(ints)

    # Merge consecutive spans
    ret = []
    cur_span = int_spans[0]
    for (start, end) in int_spans[1:]:
        if start - 1 == cur_span[-1]:
            cur_span = (cur_span[0],
                        end)
        else:
            ret.append(cur_span)
            cur_span = (start, end)

    if (not ret) or (cur_span != ret[-1]):
        ret.append(cur_span)

    return ret[0]
447233
def handle_errors(resp):
    """"""
    if resp.status_code == 400:
        raise ApiException(json.loads(resp.content).get('message'))
    return resp
1115124
def extract(format, carrier)
      case format
      when OpenTracing::FORMAT_TEXT_MAP, OpenTracing::FORMAT_BINARY
        ::Instana.logger.debug 'Unsupported extract format'
      when OpenTracing::FORMAT_RACK
        ::Instana::SpanContext.new(::Instana::Util.header_to_id(carrier['HTTP_X_INSTANA_T']),
                                     ::Instana::Util.header_to_id(carrier['HTTP_X_INSTANA_S']))
      else
        ::Instana.logger.debug 'Unknown inject format'
        nil
      end
    end
1221726
private void handleError() {
		String msg = I18nUtilities.format(UIContextHolder.getCurrent().getLocale(),
				InternalMessages.DEFAULT_CONTENT_ERROR);
		throw new ErrorCodeEscape(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, msg);
	}
776968
def handle_get(self):
        

        code = 400
        message, explain = \
                 BaseHTTPServer.BaseHTTPRequestHandler.responses[code]

        response = BaseHTTPServer.DEFAULT_ERROR_MESSAGE % { #@UndefinedVariable
             'code' : code,
             'message' : message,
             'explain' : explain
            }
        sys.stdout.write('Status: %d %s\n' % (code, message))
        sys.stdout.write('Content-Type: text/html\n')
        sys.stdout.write('Content-Length: %d\n' % len(response))
        sys.stdout.write('\n')

        sys.stdout.write(response)
467737
function(self, message) {
  var msgHeader = parseHeader(message);
  if (msgHeader.opCode === OP_COMPRESSED) {
    msgHeader.fromCompressed = true;
    var index = MESSAGE_HEADER_SIZE;
    msgHeader.opCode = message.readInt32LE(index);
    index += 4;
    msgHeader.length = message.readInt32LE(index);
    index += 4;
    var compressorID = message[index];
    index++;
    decompress(compressorID, message.slice(index), function(err, decompressedMsgBody) {
      if (err) {
        throw err;
      }
      if (decompressedMsgBody.length !== msgHeader.length) {
        throw new Error(
          'Decompressing a compressed message from the server failed. The message is corrupt.'
        );
      }
      self.messageHandler(
        new Response(self.bson, message, msgHeader, decompressedMsgBody, self.responseOptions),
        self
      );
    });
  } else {
    self.messageHandler(
      new Response(
        self.bson,
        message,
        msgHeader,
        message.slice(MESSAGE_HEADER_SIZE),
        self.responseOptions
      ),
      self
    );
  }
}
738464
def decode_rfc2231(s):
    """"""
    parts = s.split(TICK, 2)
    if len(parts) <= 2:
        return None, None, s
    return parts
992708
function stripProxyResHeaders(res) {
  return Object.entries(res.headers).reduce((memo, header) => {
    const [key, val] = header
    const invalid = [undefined, 'connection', 'content-encoding']
    if (invalid.indexOf(key) === -1) {
      memo[key] = val // eslint-disable-line
    }
    return memo
  }, {})
}
1061810
def span_context_from_string(value):
    
    if type(value) is list and len(value) > 0:
        # sometimes headers are presented as arrays of values
        if len(value) > 1:
            raise SpanContextCorruptedException(
                'trace context must be a string or array of 1: "%s"' % value)
        value = value[0]
    if not isinstance(value, six.string_types):
        raise SpanContextCorruptedException(
            'trace context not a string "%s"' % value)
    parts = value.split(':')
    if len(parts) != 4:
        raise SpanContextCorruptedException(
            'malformed trace context "%s"' % value)
    try:
        trace_id = int(parts[0], 16)
        span_id = int(parts[1], 16)
        parent_id = int(parts[2], 16)
        flags = int(parts[3], 16)
        if trace_id < 1 or span_id < 1 or parent_id < 0 or flags < 0:
            raise SpanContextCorruptedException(
                'malformed trace context "%s"' % value)
        if parent_id == 0:
            parent_id = None
        return trace_id, span_id, parent_id, flags
    except ValueError as e:
        raise SpanContextCorruptedException(
            'malformed trace context "%s": %s' % (value, e))
1207319
function handle404(url, res) {
  var json = {
    error: {
      code: 404,
      message: 'The requested URL ' + url + ' was not found on this server.'
    }
  };
  write(json, res, 404);
}
355225
function decodeStream( $request, $stream, $headers=false, $cookies=array(), $statuscode="200"  )
    {
        $this->Cookies = $cookies;
        $this->StatusCode = $statuscode;

        $ct = explode( ';', $headers['content-type'], 2 );
        switch( $ct[0] )
        {
            case 'application/json':
            case 'text/javascript':
                $results = json_decode( $stream, true );
                if ( !is_array( $results ) ||
                    !array_key_exists( 'content', $results ) ||
                    !array_key_exists( 'error_text', $results )
                    )
                {
                    // invalid ezjscore response
                    $this->IsFault = true;
                    $this->FaultCode = self::INVALIDRESPONSEERROR;
                    $this->FaultString = self::INVALIDRESPONSESTRING;
                }
                else
                {

                    if ( $results['error_text'] == '' )
                    {
                        $this->IsFault = false;
                        $this->FaultString = false;
                        $this->FaultCode = false;
                        $this->Value = $results['content'];
                    }
                    else
                    {
                        $this->IsFault = true;
                        $this->FaultCode = self::GENERICRESPONSEERROR;
                        /// @todo we should somehow typecast to string here???
                        $this->FaultString = $results['error_text'];
                    }
                }
                break;
            case 'text/xml':
            case 'application/xml':
            default:
                $this->IsFault = true;
                $this->FaultCode = self::INVALIDRESPONSEERROR;
                $this->FaultString = "Unsupported feature: decoding response in '{$ct[0]}' format";
        }
    }
1138560
private static List<SNIServerName> exploreSNIExt(ByteBuffer input,
            int extLen) throws SSLException {

        Map<Integer, SNIServerName> sniMap = new LinkedHashMap<>();

        int remains = extLen;
        if (extLen >= 2) {     // "server_name" extension in ClientHello
            int listLen = getInt16(input);     // length of server_name_list
            if (listLen == 0 || listLen + 2 != extLen) {
                throw UndertowMessages.MESSAGES.invalidTlsExt();
            }

            remains -= 2;     // 0x02: the length field of server_name_list
            while (remains > 0) {
                int code = getInt8(input);      // name_type
                int snLen = getInt16(input);    // length field of server name
                if (snLen > remains) {
                    throw UndertowMessages.MESSAGES.notEnoughData();
                }
                byte[] encoded = new byte[snLen];
                input.get(encoded);

                SNIServerName serverName;
                switch (code) {
                    case StandardConstants.SNI_HOST_NAME:
                        if (encoded.length == 0) {
                            throw UndertowMessages.MESSAGES.emptyHostNameSni();
                        }
                        serverName = new SNIHostName(encoded);
                        break;
                    default:
                        serverName = new UnknownServerName(code, encoded);
                }
                // check for duplicated server name type
                if (sniMap.put(serverName.getType(), serverName) != null) {
                    throw UndertowMessages.MESSAGES.duplicatedSniServerName(serverName.getType());
                }

                remains -= encoded.length + 3;  // NameType: 1 byte
                                                // HostName length: 2 bytes
            }
        } else if (extLen == 0) {     // "server_name" extension in ServerHello
            throw UndertowMessages.MESSAGES.invalidTlsExt();
        }

        if (remains != 0) {
            throw UndertowMessages.MESSAGES.invalidTlsExt();
        }

        return Collections.unmodifiableList(new ArrayList<>(sniMap.values()));
    }
1272630
def catch_boto_400(self, message, heading=None, document=None, **info):
        """"""
        try:
            yield
        except ClientError as error:
            if str(error.response["ResponseMetadata"]["HTTPStatusCode"]).startswith("4"):
                if heading or document:
                    print("=" * 80)
                    if heading:
                        print(heading)
                    print(document)
                    print("=" * 80)
                error_message = error.response["Error"]["Message"]
                raise BadAmazon(message, error_message=error_message, error_code=error.response["ResponseMetadata"]["HTTPStatusCode"], **info)
            else:
                raise