/** * @param ClientException $exception * @return AuthException */ private function convertException($exception) { $authException = new AuthException($exception->getResponse()->getReasonPhrase(), $exception->getCode()); $authException->setUrl($exception->getResponse()->getEffectiveUrl()); $authException->setErrors(json_decode($exception->getResponse()->getBody()->getContents())); return $authException; }
/** * Parses a ``ClientException`` for any specific exceptions thrown by the * API in the response body. If the response body is not in JSON format, * an ``Exception`` is returned. * * Check a ``ClientException`` to see if it has an associated * ``ResponseInterface`` object. * * @param ClientException $exception * @return Exception */ protected function resolveExceptionClass(ClientException $exception) { $response = $exception->getResponse()->getBody(); $response = json_decode($response->getContents()); if ($response === null) { return new Exception($exception->getMessage()); } $meta = isset($response->meta) ? $response->meta : $response; $class = '\\Larabros\\Elogram\\Exceptions\\' . $meta->error_type; return new $class($meta->error_message); }
protected function createApiMock($response, $statusCode = 200) { $jsonFile = $this->createJsonFile(); $jobsMethods = array('collectCloverXml', 'getJsonFile', 'collectGitInfo', 'collectEnvVars', 'dumpJsonFile', 'send'); $api = $this->getMockBuilder('Satooshi\\Bundle\\CoverallsV1Bundle\\Api\\Jobs')->disableOriginalConstructor()->setMethods($jobsMethods)->getMock(); $api->expects($this->once())->method('collectCloverXml')->with()->will($this->returnSelf()); $api->expects($this->once())->method('getJsonFile')->with()->will($this->returnValue($jsonFile)); $api->expects($this->once())->method('collectGitInfo')->with()->will($this->returnSelf()); $api->expects($this->once())->method('collectEnvVars')->with($this->equalTo($_SERVER))->will($this->returnSelf()); $api->expects($this->once())->method('dumpJsonFile')->with()->will($this->returnSelf()); $request = $this->getMockBuilder('\\GuzzleHttp\\Psr7\\Request')->setConstructorArgs(['POST', '/'])->getMock(); if ($statusCode === 200) { $api->expects($this->once())->method('send')->with()->will($this->returnValue($response)); } else { if ($statusCode === null) { $exception = \GuzzleHttp\Exception\ConnectException::create($request); } elseif ($statusCode === 422) { $exception = \GuzzleHttp\Exception\ClientException::create($request, $response); } else { $exception = \GuzzleHttp\Exception\ServerException::create($request, $response); } $api->expects($this->once())->method('send')->with()->will($this->throwException($exception)); } return $api; }
/** * Create an ApiException from a client exception. * * @param ClientException $e The client exception. * @return ApiException */ protected function createApiException(ClientException $e) { $response = $e->getResponse(); if ($response->getStatusCode() === 401 || $response->getStatusCode() === 403) { throw new ApiKeyInvalidException(); } throw new ApiException((string) $response->getBody()); }
private function prepareException(ClientException $ce) { $message = 'An error occured'; $body = json_decode($ce->getResponse()->getBody()); if (!$body) { return $message; } return $body->message; }
/** * @param ClientException $e * * @return AbstractRateLimitException */ protected function handleRateLimitException(ClientException $e) { if ($e->getResponse()->getHeader(self::HEADER_RATE_LIMIT_TYPE)[0] === self::RATE_LIMIT_TYPE_USER) { $exception = new UserRateLimitException(); } else { $exception = new ServiceRateLimitException(); } return $exception->setClientException($e)->setRetryAfter($e->getResponse()->getHeader(self::HEADER_RETRY_AFTER)[0]); }
/** * Handles the Guzzle client exception. * * @param ClientException $e * @throws Unauthorized * @throws AddressNotFound */ protected function handleClientException(ClientException $e) { switch ($e->getCode()) { case 401: throw new Unauthorized(); case 404: throw new AddressNotFound(); } }
/** * @param ClientException $baseException * @return SalesforceRestApiException */ public function create(ClientException $baseException) { $message = ''; $errorResponse = json_decode($baseException->getResponse()->getBody()->getContents(), true); if (isset($errorResponse['error'])) { $message = $errorResponse['error_description']; } elseif (isset($errorResponse[0])) { $message = $errorResponse[0]['message']; } return new SalesforceRestApiException($message, 400); }
function it_maps_declined_response_402_to_payment_result_object(ClientException $exception, Response $response, ResultObjectMapperInterface $resultMapper, MethodInterface $method) { $result = ['error' => 'Error string']; $resultObject = new Payment(); $response->getStatusCode()->willReturn(402); $response->json()->willReturn($result); $method->createResultObject()->willReturn($resultObject); $exception->getResponse()->willReturn($response); $resultMapper->map($result, $resultObject)->shouldBeCalled()->willReturn($resultObject); $this->get($exception, $method)->getResult()->shouldReturn($resultObject); }
/** * Constructor. * * @param \GuzzleHttp\Exception\ClientException $exception * @return void * @throws \Cartalyst\Stripe\Exception\StripeException */ public function __construct(ClientException $exception) { $response = $exception->getResponse(); $statusCode = $response->getStatusCode(); $error = json_decode($response->getBody(true), true)['error']; $errorCode = isset($error['code']) ? $error['code'] : null; $errorType = isset($error['type']) ? $error['type'] : null; $message = isset($error['message']) ? $error['message'] : null; $missingParameter = isset($error['param']) ? $error['param'] : null; $this->handleException($message, $statusCode, $errorType, $errorCode, $missingParameter); }
private function throwException(ClientException $e, $entity_name) { $error_data = $e->getResponse()->json(); switch ($error_data["error"]) { case 'invalid_resource': $exception = new ResourceInvalidException("Algunos campos son incorrectos en " . $entity_name); $exception->error_messages = $error_data["messages"]; throw $exception; break; default: throw new ResourceInvalidException("Petición fallida"); } }
/** * Parse an exception and return its body's error message. * * @param ClientException $guzzleException * * @return string */ protected function parseErrorMessage(ClientException $guzzleException) { $response = $guzzleException->getResponse(); if ($this->isJsonResponse($response)) { $array = $response->json(); if (isset($array['message'])) { return $array['message']; } if (isset($array['error_description'])) { return $array['error_description']; } } return (string) $response->xml()->message; }
public function postCheck(Request $request) { $this->validate($request, ['number' => 'required']); $device = JWTAuth::parseToken()->toUser(); $countryCode = strtoupper($device->country_code); if ($device->credits <= 0) { throw new \Exception("Insufficient balance", 403); } $client = new Client(); $res = $client->get('https://lookups.twilio.com/v1/PhoneNumbers/' . $request->input('number'), ['auth' => [env('TWILIO_KEY'), env('TWILIO_SECRET')], 'query' => ['Type' => 'carrier', 'CountryCode' => $countryCode], 'exceptions' => false]); if ($res->getStatusCode() == 200) { $device->credits--; $device->save(); $response = json_decode($res->getBody(), true); if ($response['carrier']['name'] == null) { return ['error' => 404, 'credits' => $device->credits]; } return ['country_code' => $response['country_code'], 'phone_number' => $response['phone_number'], 'carrier_name' => $response['carrier']['name'], 'number_type' => $response['carrier']['type'], 'credits' => $device->credits]; } else { if ($res->getStatusCode() == 404) { return ['error' => 404, 'credits' => $device->credits]; } else { throw new \Exception(ClientException::getMessage(), 500); } } }
/** * Create an ApiException from a client exception. * * @param ClientException $e The client exception. * @return ApiException * @throws \Speicher210\KontaktIO\Exception\ApiKeyInvalidException */ protected function createApiException(ClientException $e) { $response = $e->getResponse(); if (in_array($response->getStatusCode(), array(401, 403), true)) { throw new ApiKeyInvalidException($response); } if ($response->getBody()->getSize() > 0) { /** @var ApiErrorResponse $apiErrorResponse */ $apiErrorResponse = $this->serializer->deserialize($e->getResponse()->getBody(), ApiErrorResponse::class, 'json'); } else { $apiErrorResponse = new ApiErrorResponse(); $apiErrorResponse->setStatus($response->getStatusCode()); $apiErrorResponse->setMessage($response->getReasonPhrase()); } return new ApiException($apiErrorResponse, $e); }
/** * Handle client error exceptions * * @param \GuzzleHttp\Exception\ClientException $exc * @throws \WalmartApiClient\Exception\ApiForbiddenException * @throws \WalmartApiClient\Exception\ApiNotFoundException * @throws \WalmartApiClient\Exception\ApiRequestUriTooLongException * @throws \WalmartApiClient\Exception\ApiBadRequestException */ protected function handleClientException(\GuzzleHttp\Exception\ClientException $exc) { if ($exc->hasResponse() && isset(json_decode($exc->getResponse()->getBody(), true)['errors'])) { $exception = array_shift(json_decode($exc->getResponse()->getBody(), true)['errors']); switch ($exception['code']) { case 403: throw new \WalmartApiClient\Exception\ApiForbiddenException($exception['message'], $exception['code']); case 404: throw new \WalmartApiClient\Exception\ApiNotFoundException($exception['message'], $exception['code']); case 414: throw new \WalmartApiClient\Exception\ApiRequestUriTooLongException($exception['message'], $exception['code']); default: throw new \WalmartApiClient\Exception\ApiBadRequestException($exception['message'], $exception['code']); } } throw new \WalmartApiClient\Exception\ApiBadRequestException('Bad Request', 400); }
/** * Parse an exception and return its body's error message. * * @param ClientException $guzzleException * * @return string */ protected function parseErrorMessage(ClientException $guzzleException) { $response = $guzzleException->getResponse(); if ($this->isJsonResponse($response)) { $array = $response->json(); if (isset($array['message'])) { return $array['message']; } if (isset($array['error_description'])) { return $array['error_description']; } } try { return (string) $response->xml()->message; } catch (\Exception $ex) { return 'Excpetion while processing error response. Error reason phrase: ' . $response->getReasonPhrase(); } }
function __construct(ClientException $badResponseException) { $message = $badResponseException->message; $response = $badResponseException->getResponse()->getBody(); $response = json_decode($response); //Add rev data to the message for easy debugging if ($response && is_object($response)) { if (isset($response->code, $response->message)) { $this->rev_code = $response->code; $this->rev_message = $response->message; } $message .= PHP_EOL; foreach (get_object_vars($response) as $key => $value) { $message .= '[rev ' . $key . '] ' . $value . PHP_EOL; } } parent::__construct($message, $badResponseException->code, $badResponseException); }
/** * @param ClientException $clientException * * @return ApiException | SearchLimitException */ public static function createThrowable(ClientException $clientException) { $data = \GuzzleHttp\json_decode($clientException->getResponse()->getBody()->getContents()); $code = 0; $message = ''; if (!empty($data->error)) { $error = $data->error; if (!empty($error->code)) { $code = $error->code; } if (!empty($error->message)) { $message = $error->message; } } if ($code == SearchLimitException::EXCEPTION_CODE) { return new SearchLimitException($message); } return new ApiException($message, $code); }
/** * @covers ::execute */ public function testExecuteWithResponseFailure() { $code = 1337; $message = 'hello world'; $this->setExpectedException(RuntimeException::class, $message, $code); $request = $this->getMock(RequestInterface::class); $response = $this->createResponse(400, ['error' => ['code' => $code, 'message' => $message]]); $exception = ClientException::create($request, $response); $this->internalClient->expects($this->once())->method('post')->will($this->throwException($exception)); $this->client->execute(static::SQL, ['foo' => 'bar']); }
public function handleHttpClientException(HttpClientException $e) { switch ($e->getResponse()->getStatusCode()) { case self::CONFLICT: throw new ProxyExistsException($e->getResponse()->getBody(), $e->getCode(), $e); case self::NOT_FOUND: throw new NotFoundException($e->getResponse()->getBody(), $e->getCode(), $e); case self::BAD_REQUEST: throw new InvalidToxicException($e->getResponse()->getBody(), $e->getCode(), $e); default: throw $e; } }
/** * @param ClientException $exception * @return \Exception */ protected function resolveExceptionClass(ClientException $exception) { $response = $exception->getResponse()->getBody(); $response = json_decode($response->getContents()); if ($response === null) { return new \Exception($exception->getMessage()); } if (!empty($response->message)) { $message = (string) $response->message; } elseif (!empty($response->errors)) { $message = $response->errors; if (is_array($response->errors)) { $message = []; foreach ($response->errors as $error) { $message[] = $error->message; } $message = implode(PHP_EOL, $message); } } else { $message = (string) $response; } return new \Exception($message); }
/** * Handling non 200 http request. * * @param \GuzzleHttp\Exception\ClientException $e * The client exception handler. * * @throws Exception */ private function handleExceptions(\GuzzleHttp\Exception\ClientException $e, $return = FALSE) { $json = $e->getResponse()->json(); $implode = array(); if (!empty($json['errors'])) { foreach ($json['errors'] as $errors) { foreach ($errors as $error) { $implode[] = $error; } } } else { $implode[] = $json['title']; } $errors = implode(', ', $implode); if ($return) { return $errors; } throw new Exception('Your request has failed: ' . $errors); }
/** * Handle http client exceptions * * @param HttpClientException $e * * @return void * @throws Exception */ private function handleRequestException(HttpClientException $e) { if ($response = $e->getResponse()) { $exception = new Exception($response->getReasonPhrase(), $response->getStatusCode(), $e); $exception->setBody(json_decode($response->getBody())); throw $exception; } throw new Exception($e->getMessage(), 500, $e); }
/** * @param HttpClientException $exception * @throws TransportException */ protected function handleClientException(HttpClientException $exception) { switch ($exception->getResponse()->getStatusCode()) { case 401: throw new UnauthorizedException("Unauthorized API request."); default: throw new ClientException($exception->getMessage()); } }
/** * Parse the client error and return the error message thrown. * @param ClientException $e * @return string */ private function parseClientError(ClientException $e) { $msg = ""; if ($e->getResponse() != null && $e->getResponse()->getBody() != null) { $json = json_decode($e->getResponse()->getBody()->getContents(), true); $msg = isset($json['error']) ? $json['error'] : ""; } return $msg; }
/** * @param ClientException $e * @throws Exception */ private function exceptionHasResponse(ClientException $e) { if ($e->hasResponse()) { $json = (string) $e->getResponse()->getBody(); $output = json_decode($json, true); if (empty($output['error'])) { throw new Exception("An error response was returned but the content could not be parsed: {$json}"); } $exception_message = []; foreach ($output['error'] as $field => $error_message) { $exception_message[] = "For field '{$field}' the API reported: {$error_message}"; } throw new Exception(implode("\n", $exception_message)); } }
public function __construct($message, $request, $response, $previous) { $this->response = $response->getBody()->getContents(); $message = join('<br />', $this->getMessages()); parent::__construct($message, $request, $response, $previous); }
function it_wraps_client_exceptions_with_ours(MethodInterface $method, ClientInterface $client, RequestInterface $request, ExceptionMapper $mapper, ClientException $exception) { $client->send($request)->willThrow($exception->getWrappedObject()); $mapper->get($exception->getWrappedObject(), $method)->shouldBeCalled()->willThrow('Cardinity\\Exception\\Request'); $this->shouldThrow('Cardinity\\Exception\\Request')->duringSendRequest($method, 'POST', 'https://api.cardinity.com/v1/'); }
/** * Turns a ClientException into a TiketException - like magic. * @param ClientException $exception - Guzzle ClientException * @return TiketException */ protected function convertException($exception) { $tiketException = new TiketException($exception->getResponse()->getReasonPhrase(), $exception->getCode()); $tiketException->setUrl($exception->getResponse()->getEffectiveUrl()); $tiketException->setErrors(json_decode($exception->getResponse()->getBody()->getContents())); return $tiketException; }
public function handleClientException(ClientException $e, $data = []) { $contents = json_decode($e->getResponse()->getBody()->getContents()); $exception = new RemoteException($e->getMessage()); $exception->data = $data; $exception->headers = $e->getRequest()->getHeaders(); $exception->setErrorCode(isset($contents->errors) ? $contents->errors[0]->code : null); $exception->setError(isset($contents->errors) ? $contents->errors[0]->description : ''); throw $exception; }