Thrown when an response could not be JSON decoded.

@param ResponseInterface $response The response that couldn't be decoded.
@param string $error The decode error message.

@return static
557923
public static function failedToDecodeResponse(ResponseInterface $response, $error)
    {
        $response->getBody()->rewind();
        return new static(sprintf(
            "Failed to decode response '%s' with error '%s'",
            $response->getBody()->getContents(),
            $error
        ));
    }
597882
private function checkError(ResponseInterface $response, $url)
    {
        if (($response->getStatusCode() == 200) || ($response->getStatusCode() == 201)) {
            return;
        }

        switch ($response->getHeader('Content-Type')) {
            case 'text/plain':
                throw new \RuntimeException('Error: ' . $response->getBody() . ' URI: ' . $url);
            case 'application/json':
                $error = json_decode($response->getBody());
                if (isset($error->message)) {
                    throw new \RuntimeException($error->message . ' URI: ' . $url);
                }
                break;
            default:
                throw new \RuntimeException(
                    'Unknown Error: No error message was returned from the server - Code: ' . $response->getStatusCode(
                    ) . ' URI: ' . $url
                );
        }
    }
946984
public static function decodeHttpResponse($response) {
    $code = $response->getResponseHttpCode();
    $body = $response->getResponseBody();
    $decoded = null;
    
    if ((intVal($code)) >= 300) {
      $decoded = json_decode($body, true);
      $err = 'Error calling ' . $response->getRequestMethod() . ' ' . $response->getUrl();
      if ($decoded != null && isset($decoded['error']['message'])  && isset($decoded['error']['code'])) {
        // if we're getting a json encoded error definition, use that instead of the raw response
        // body for improved readability
        $err .= ": ({$decoded['error']['code']}) {$decoded['error']['message']}";
      } else {
        $err .= ": ($code) $body";
      }

      throw new ServiceException($err, $code, null, $decoded['error']['errors']);
    }
    
    // Only attempt to decode the response, if the response code wasn't (204) 'no content'
    if ($code != '204') {
      $decoded = json_decode($body, true);
      if ($decoded === null || $decoded === "") {
        throw new ServiceException("Invalid json in service response: $body");
      }
    }
    return $decoded;
  }
1060405
protected function response($response) {
    // Check for HTTP response error codes.
    if ($this->client->error) {
      $this->onErrorResponse(
        $this->client->errorCode,
        $this->client->errorMessage,
        $response
      );
    }
    else {
      $this->onSuccessfulResponse($response);
    }
    return $response;
  }
985927
private function throwExceptionOnHttpErrors(Response $response)
    {
        $httpCode = $response->getHttpCode();

        if ($httpCode >= 400)
        {
            // Get the description of the http error code
            $httpMessage = $response->getHttpMessage($httpCode);

            throw new HttpException($response, $httpMessage, $httpCode);
        }
    }
665223
private function withError(ResponseInterface $response, $throwable)
    {
        $detail = 'Internal Server Error';
        $extensions = [];

        if ($this->displayErrorDetails) {
            $throwables = $this->unpackThrowables($throwable);
            $extensions['error_details'] = $this->formatStacktraceForExceptions($throwables);

            $detail = $throwable->getMessage();
        }

        $problem = new HTTPProblem(500, $detail, $extensions);
        return $this->renderProblem($response, $this->renderer, $problem);
    }
514464
public static function clientException(ResponseInterface $response, $data)
    {
        return static::fromResponse(
            $response,
            isset($data['message']) ? $data['message'] : json_encode($data)
        );
    }
943747
public function canResponseSatisfyFailedRequest(RequestInterface $request, Response $response)
    {
        $reqc = $request->getHeader('Cache-Control');
        $resc = $response->getHeader('Cache-Control');
        $requestStaleIfError = $reqc ? $reqc->getDirective('stale-if-error') : null;
        $responseStaleIfError = $resc ? $resc->getDirective('stale-if-error') : null;

        if (!$requestStaleIfError && !$responseStaleIfError) {
            return false;
        }

        if (is_numeric($requestStaleIfError) && $response->getAge() - $response->getMaxAge() > $requestStaleIfError) {
            return false;
        }

        if (is_numeric($responseStaleIfError) && $response->getAge() - $response->getMaxAge() > $responseStaleIfError) {
            return false;
        }

        return true;
    }
245063
public static function factory(RequestInterface $request, Response $response)
    {
        $message = 'Client error response' . PHP_EOL . implode(PHP_EOL, array(
            '[status code] ' . $response->getStatusCode(),
            '[reason phrase] ' . $response->getReasonPhrase(),
            '[url] ' . $request->getUrl(),
        ));

        $e = new static($message);
        $e->setResponse($response);
        $e->setRequest($request);

        return $e;
    }
1045387
private function withError(ResponseInterface $response, $throwable)
    {
        if ($throwable instanceof ErrorException) {
            $severity = ErrorHandler::getErrorType($throwable->getSeverity());
        } else {
            $severity = 'Error';
        }

        $contents = [
            'message' => 'Application Error',
            'status' => 500,
            'severity' => $severity,
            'throwable' => $throwable,
        ];

        if ($this->displayErrorDetails) {
            $throwables = $this->unpackThrowables($throwable);
            $contents['details'] = $this->formatStacktraceForExceptions($throwables);
            $contents['message'] = $throwable->getMessage();
        }

        return $this
            ->withHTML($response, $contents)
            ->withStatus(500);
    }
1130058
protected function handleErrors(ResponseInterface $response)
    {
        $body = $response->getBody()->__toString();
        switch ($response->getStatusCode()) {
            case 400:
                throw new DomainExceptions\BadRequestException($body);
                break;

            case 403:
                throw new DomainExceptions\ForbiddenException();
                break;

            case 404:
                throw new DomainExceptions\NotFoundException();
                break;

            case 500:
                throw new DomainExceptions\ServerErrorException();
                break;

            default:
                throw new DomainExceptions\UnknownErrorException();
                break;
        }
    }
788909
private function getMessage($error, ServerRequestInterface $request, ResponseInterface $response)
    {
        if ($error instanceof ApiException) {
            $message = $error->getArrayMessage();
            return !empty($message) ? $message : $error->getMessage();
        }

        if ($error instanceof \Throwable) {
            return $error;
        }

        return 'An error ocurred.';
    }
588157
protected function handleResponse( ResponseInterface $response ){

        $body = json_decode($response->getBody(), true);

        // The expected response should always be JSON, thus now an array.
        if( !is_array($body) ){
            throw new Exception\ApiException( 'Malformed JSON response from server', $response->getStatusCode(), $body, $response );
        }

        return $body;

    }
311169
private function validateResponse(ResponseInterface $response)
    {
        if ($response->getStatusCode() !== 200) {
            $responseData = json_decode((string) $response->getBody(), true);
            $code = isset($responseData['error']['code']) ? $responseData['error']['code'] : 0;
            $message = isset($responseData['error']['message']) ? $responseData['error']['message'] : $response->getReasonPhrase();

            throw new ApiException($message, $code, $responseData);
        }
    }
1031631
private function withError(ResponseInterface $response, $throwable)
    {
        $contents = [
            'error' => 'Application Error',
        ];

        if ($this->displayErrorDetails) {
            $throwables = $this->unpackThrowables($throwable);
            $contents = [
                'error' => $throwable->getMessage(),
                'details' => $this->formatStacktraceForExceptions($throwables),
            ];
        }

        return $this
            ->withJSON($response, $contents)
            ->withStatus(500);
    }
1102182
public static function buildFromPsrResponse(ResponseInterface $response)
    {
        return new static(
            $response->getStatusCode(),
            $response->getHeaders(),
            $response->getBody(),
            $response->getProtocolVersion(),
            $response->getReasonPhrase()
        );
    }
683532
protected function getResponseAsJson( ResponseInterface $response ) {
        if( $response->hasHeader('Content-Type') ) {
            $typeHeader = $response->getHeader('Content-Type');
            $contentType = array_shift($typeHeader);

            if( stripos( $contentType, 'application/json' ) === 0 ) {
                return json_decode($response->getBody(), false);
            }
        }

        return null;
    }