@param $response_body
@param $response_code
@param $response_headers
@param $json_resp

@throws ApiException
@throws Conflict
@throws Forbidden
@throws InvalidRequest
@throws Unauthorized
513988
private function handleApiError(
        $response_body,
        $response_code,
        $response_headers,
        $json_resp
    ) {

        switch ($response_code) {
            case 400:
                // format for the errors:
                // - [{"field":"amount","message":"Can refund at most GBP 0"}]
                // - [{"code":2,"text":"Invalid card details", "client": true, "merchant": false}]
                $message = "Bad (invalid) request";
                // @TODO - extract error parsing logic
                if ($json_resp && is_array($json_resp) && ! empty($json_resp)) {
                    if (isset($json_resp[0]['message'])) {
                        $message = $json_resp[0]['message'];
                    } else if (isset($json_resp[0]['text'])) {
                        $message = $json_resp[0]['text'];
                    }
                }
                throw new InvalidRequest($message,
                    $response_code, $response_body, $json_resp,
                    $response_headers);
            case 401:
                throw new Unauthorized("You need to provide credentials (an app's API key).",
                    $response_code,
                    $response_body, $json_resp,
                    $response_headers);
            case 403:
                throw new Forbidden("You are correctly authenticated but do not have access.",
                    $response_code, $response_body,
                    $json_resp,
                    $response_headers);
            case 404:
                throw new NotFound("Resource not found.",
                    $response_code, $response_body,
                    $json_resp,
                    $response_headers);
            case 409:
                throw new Conflict("Everything you submitted was fine at the time of validation, but something changed in the meantime and came into conflict with this (e.g. double-capture).",
                    $response_code, $response_body,
                    $json_resp,
                    $response_headers);
            default:
                throw new ApiException("Unknown api error",
                    $response_code,
                    $response_body,
                    $json_resp,
                    $response_headers);
        }
    }
59887
function onResponse(httpCode, headers, body, callback) {
  var resp = {
    _HTTP: {
      status: httpCode
    },
    headers: headers
  };
  var i;
  var pieces;

  if(typeof body === 'string') {
    try {
      //JSON decode
      resp.body = (body.length > 0 && decodeJSON) ? JSON.parse(body) : body;
    }
    catch(e) {
      //failed to decode - likely not JSON
      resp.body = body;
    }
  }

  //will likely only happen in node due to httpOnly cookies
  if(headers['set-cookie']) {
    resp.cookies = {};

    for(i in headers['set-cookie']) {
      if(headers['set-cookie'].hasOwnProperty(i)) {
        pieces = headers['set-cookie'][i].split(';')[0].split('=');
        resp.cookies[pieces[0]] = pieces[1];
        pieces = null;
      }
    }
  }

  if(resp._HTTP.status >= 400) {
    observers._notify('error', resp);
  }

  if(typeof callback === 'function') {
    callback(resp, (resp._HTTP.status < 400));
  }
}
682420
public static JSONObject processBadRespStr(int responseCode, String responseMsg) throws JSONException {

        JSONObject response = new JSONObject();
        response.put("responseCode", responseCode);
        if (responseMsg.equalsIgnoreCase("")) { // good response is empty string
            response.put("responseMsg", "");
        } else { // bad response is json string
            JSONObject errorObject = new JSONObject(responseMsg).optJSONObject("odata.error");

            String errorCode = errorObject.optString("code");
            String errorMsg = errorObject.optJSONObject("message").optString("value");
            response.put("responseCode", responseCode);
            response.put("errorCode", errorCode);
            response.put("errorMsg", errorMsg);
        }

        return response;
    }
116004
public function request(string $method, string $url, array $headers = [], string $body = ''): ResponseInterface
    {
        $request = Factory::request($method, $url, $headers, $body);

        return $this->sendRequest($request);
    }
127709
public function respond($statusCode = 200, $headers = [], $options = 0)
    {
        $response = new JsonResponse();

        $response->setData($this->createData()->toArray());

        if (is_int($statusCode)) {
            $statusCode = function (JsonResponse $response) use ($statusCode) {
                return $response->setStatusCode($statusCode);
            };
        }

        if (is_array($headers)) {
            $headers = function (JsonResponse $response) use ($headers) {
                return $response->withHeaders($headers);
            };
        }

        if (is_int($options)) {
            $options = function (JsonResponse $response) use ($options) {
                $response->setEncodingOptions($options);

                return $response;
            };
        }

        if (is_callable($options)) {
            $options($response);
        }

        if (is_callable($statusCode)) {
            $statusCode($response);
        }

        if (is_callable($headers)) {
            $headers($response);
        }

        return $response;
    }
956509
public function error( $code = 404, $msg = "Resource not found" )
	{
		$request = HttpFactory::i()->request();

		if ( $request->ajax() || $request->wantsJson() )
			return new JsonResponse( ['error' => $msg] );
		else
			return new Response( Redirect::back()->withInput( $request->input() )->withErrors( ['error' => $msg] ) );
	}
388589
public function process(
        ServerRequestInterface $request,
        DelegateInterface $delegate
    ): JsonResponse {
        if (!$this->isAllowed->__invoke($request, 'sites', 'admin')) {
            return new JsonResponse(['error' => 'unauthorized'], 401);
        }

        $sectionName = $request->getAttribute('sectionName');

        try {
            $settings = $this->getSection->__invoke(
                $this->currentSite,
                $sectionName
            );
        } catch (InvalidSectionNameException $e) {
            return new JsonResponse(['error' => 'invalid section name'], 400);
        }

        if ($settings === null) {
            return new JsonResponse(['error' => 'settings not found'], 404);
        }

        return new JsonResponse($settings);
    }
809251
protected function response($respBody, $respHeaders, $respCode)
    {
        // Handle non successful HTTP status codes
        if ($respCode > 400) {
            $type = $respCode > 500 ? 'Internal error' : 'Request error';
            throw new GeneralException(
                'The request to NeverBounce was unsuccessful '
                . 'Try the request again, if this error persists'
                . ' let us know at support@neverbounce.com.'
                . "\n\n($type [status $respCode: $respBody])"
            );
        }

        // Check that the response type is expected
        $contentType = $respHeaders['content-type'];
        if ($this->acceptedType !== $contentType) {
            throw new GeneralException(
                'The request to NeverBounce was unsuccessful '
                . "Expected a response type of '{$this->acceptedType}' but "
                . "received a response type of '{$contentType}. "
                . 'Try the request again, if this error persists'
                . ' let us know at support@neverbounce.com.'
                . "\n\n(Unexpected Type [status $respCode: $respBody])"
            );
        }

        // Handle response based on Content-Type
        if ($this->acceptedType === 'application/json') {
            return $this->jsonResponse($respBody, $respCode);
        }

        return $this->decodedResponse = $respBody;
    }
1278390
function writeError(code, res, msg) {
	try{
		if (res.headerSent) {
			logger.error("header Sent:", res.req.method, res.req.originalUrl);
		}
		if (httpCodeMapping) {
			code = mapHttpStatusCode(code);
		}
		msg = msg instanceof Error ? msg.message : msg;
		addStrictTransportHeaders(res);
		setResponseNoCache(res);
		if (typeof msg === 'string') {
			var err = JSON.stringify({Severity: "Error", Message: msg});
			res.setHeader('Content-Type', 'application/json');
			res.setHeader('Content-Length', err.length);
			res.writeHead(code);
			res.end(err);
		} else {
			res.writeHead(code);
			res.end();
		}
	}catch(err){
		logger.error(res.req.originalUrl , err.message);
		throw err;
	}
}
943120
public function validateResponse(Requests_Response $res)
    {
        $body = json_decode($res->body, true);

        if ($res->status_code != 200 || (isset($body['code']) && $body['code'] != 200)) {
            $message = sprintf('Request Error [%d]: %s', $res->status_code, $res->body);
            throw new \Exception($message, $res->status_code);
        }
    }
1007643
protected function readResponseHeader(&$error_code, &$error_string)
  { 
    PHPCrawlerBenchmark::reset("server_response_time");
    PHPCrawlerBenchmark::start("server_response_time");
    
    $status = socket_get_status($this->socket);
    $source_read = "";
    $header = "";
    $server_responded = false;
    
    while ($status["eof"] == false)
    {
      socket_set_timeout($this->socket, $this->socketReadTimeout);
      
      // Read line from socket
      $line_read = fgets($this->socket, 1024);
      
      // Server responded
      if ($server_responded == false)
      {
        $server_responded = true;
        $this->server_response_time = PHPCrawlerBenchmark::stop("server_response_time");
    
        // Determinate socket prefill size
        $status = socket_get_status($this->socket);
        $this->socket_prefill_size = $status["unread_bytes"];
        
        // Start data-transfer-time bechmark
        PHPCrawlerBenchmark::reset("data_transfer_time");
        PHPCrawlerBenchmark::start("data_transfer_time");
      }
      
      $source_read .= $line_read;
      
      $this->global_traffic_count += strlen($line_read);
      
      $status = socket_get_status($this->socket);
      
      // Socket timed out
      if ($status["timed_out"] == true)
      {
        $error_code = PHPCrawlerRequestErrors::ERROR_SOCKET_TIMEOUT;
        $error_string = "Socket-stream timed out (timeout set to ".$this->socketReadTimeout." sec).";
        return $header;
      }
      
      // No "HTTP" at beginnig of response
      if (strtolower(substr($source_read, 0, 4)) != "http")
      {
        $error_code = PHPCrawlerRequestErrors::ERROR_NO_HTTP_HEADER;
        $error_string = "HTTP-protocol error.";
        return $header;
      }
      
      // Header found and read (2 newlines) -> stop
      if (substr($source_read, -4, 4) == "\r\n\r\n" || substr($source_read, -2, 2) == "\n\n")
      {
        $header = substr($source_read, 0, strlen($source_read)-2);
        break;
      }
    }
    
    // Stop data-transfer-time bechmark
    PHPCrawlerBenchmark::stop("data_transfer_time");
    
    // Header was found
    if ($header != "")
    {
      // Search for links (redirects) in the header
      $this->LinkFinder->processHTTPHeader($header);
      $this->header_bytes_received = strlen($header);
      return $header;
    }
        
    // No header found
    if ($header == "")
    {
      $this->server_response_time = null;
      $error_code = PHPCrawlerRequestErrors::ERROR_NO_HTTP_HEADER;
      $error_string = "Host doesn't respond with a HTTP-header.";
      return null;
    }
  }
427102
public function makeJsonReponse($status_code, $body)
    {
        $this->getResponse()->setBody(json_encode($body, JSON_UNESCAPED_SLASHES));
        $this->getResponse()->setStatusCode($status_code);
        $this->getResponse()->addHeader("Content-type", "application/json");

        return $this->getResponse();
    }
560483
public function respond(array $data, $status = 200, $code, array $headers = [], $options = 0)
    {
        return $this->response->json(
            array_merge(compact('status', 'code'), $data), $status, $headers, $options
        );
    }
97327
final public static function print_json(
		int $errno=0, $data=null, int $http_code=200, int $cache=0
	) {
		$json = json_encode(compact('errno', 'data'));
		self::start_header($http_code, $cache, [
			'Content-Length: ' . strlen($json),
			'Content-Type: application/json',
		]);
		static::halt($json);
	}
479457
protected function respond($response, $status, $body)
    {
        $response->status($status);

        $response->end($body);
    }
824736
public function data($data, $type = 'auto', $code = 200, $header = [], $options = [])
    {
        $type == 'auto' && $type = is_array($data) ? 'json' : '';
        $response = \think\Response::create($data, $type, $code, $header, $options);
        throw new HttpResponseException($response);
    }
237963
protected function response($data, $statusCode = 200, array $headers = [])
    {
        if ($data instanceof Arrayable && !$data instanceof JsonSerializable) {
            $data = $data->toArray();
        }

        return new JsonResponse($data, $statusCode, $headers);
    }