/** * @inheritdoc * * Modifies Guzzle error messages to add more detail, based on the response * body. */ public static function create(RequestInterface $request, ResponseInterface $response = null, \Exception $previous = null) { $e = parent::create($request, $response, $previous); if ($response === null) { return $e; } $originalMessage = $e->getMessage(); $message = $originalMessage; $responseInfoProperties = ['message', 'detail', 'error', 'error_description']; try { $response->getBody()->seek(0); $json = $response->json(); foreach ($responseInfoProperties as $property) { if (!empty($json[$property])) { $message .= " [{$property}] " . implode('; ', (array) $json[$property]); } } } catch (ParseException $parseException) { // Occasionally the response body may not be JSON. $response->getBody()->seek(0); $body = $response->getBody()->getContents(); if ($body) { $message .= ' [extra] Non-JSON response body'; $message .= ' [body] ' . $body; } else { $message .= ' [extra] Empty response body'; } } // Re-create the exception to alter the message. if ($message !== $originalMessage) { $className = get_class($e); $e = new $className($message, $e->getRequest(), $e->getResponse()); } return $e; }
/** * @param ResponseInterface $response * @param string $key * * @throws RepresentationErrorException on 422 response * @throws ClientException on 4xx errors * @throws ServerException on 5xx errors * @throws BadResponseException when key is not found in response data * @return array|bool */ private function processResponse(ResponseInterface $response, $key = null) { $status = $response->getStatusCode(); if (204 == $status) { return true; } $decoded = $response->json(); $decoded = Convert::objectToArray($decoded); if (422 == $status) { //@codeCoverageIgnoreStart throw new RepresentationErrorException('', $this->client->getLastRequest(), $response); //@codeCoverageIgnoreEnd } if (200 <= $status && 300 > $status) { $this->lastResponse = $response; if (null === $key) { return $decoded; } if (false === array_key_exists($key, $decoded)) { //@codeCoverageIgnoreStart $message = sprintf('Key "%s" not found in data', $key); throw new BadResponseException($message, $this->client->getLastRequest(), $response); //@codeCoverageIgnoreEnd } return $decoded[$key]; } //@codeCoverageIgnoreStart throw BadResponseException::create($this->client->getLastRequest(), $response); //@codeCoverageIgnoreEnd }