/** * Get a response summary (useful for exceptions). * Use Guzzle method if available (Guzzle 6.1.1+). * * @param ResponseInterface $response * * @return string */ public static function getResponseBodySummary(ResponseInterface $response) { if (method_exists(RequestException::class, 'getResponseBodySummary')) { return RequestException::getResponseBodySummary($response); } $body = \GuzzleHttp\Psr7\copy_to_string($response->getBody()); if (strlen($body) > 120) { return substr($body, 0, 120) . ' (truncated...)'; } return $body; }
public function testInterceptsWithEvent() { $client = new Client(); $request = new Request('GET', '/'); $response = new Response(404); $transaction = new Transaction($client, $request); $except = new RequestException('foo', $request, $response); $event = new ErrorEvent($transaction, $except); $event->throwImmediately(true); $this->assertTrue($except->getThrowImmediately()); $event->throwImmediately(false); $this->assertFalse($except->getThrowImmediately()); $this->assertSame($except, $event->getException()); $this->assertSame($response, $event->getResponse()); $this->assertSame($request, $event->getRequest()); $res = null; $request->getEmitter()->on('complete', function ($e) use(&$res) { $res = $e; }); $good = new Response(200); $event->intercept($good); $this->assertTrue($event->isPropagationStopped()); $this->assertSame($res->getClient(), $event->getClient()); $this->assertSame($good, $res->getResponse()); }
/** * @internal * @param RequestException $e * @return AccessDeniedException|ApiException|AuthenticationException|ConflictingStateException| * MethodNotAllowedException|NotFoundException|RateLimitExceededException|UnsupportedAcceptHeaderException| * UnsupportedContentTypeException|ValidationException */ public static function create(RequestException $e) { if ($response = $e->getResponse()) { switch ($response->getStatusCode()) { case 400: return new ValidationException($e); case 401: return new AuthenticationException($e); case 403: return new AccessDeniedException($e); case 404: return new NotFoundException($e); case 405: return new MethodNotAllowedException($e); case 406: return new UnsupportedAcceptHeaderException($e); case 409: return new ConflictingStateException($e); case 415: return new UnsupportedContentTypeException($e); case 429: return new RateLimitExceededException($e); } } return new ApiException($e); }
private function handleException(RequestException $exception) { if ($exception instanceof BadResponseException) { return $exception->getResponse(); } throw new Exception($exception->getMessage()); }
private function manejar_excepcion_request(RequestException $e) { $msg = $e->getRequest() . "\n"; if ($e->hasResponse()) { $msg .= $e->getResponse() . "\n"; } throw new toba_error($msg); }
protected function failBecauseOfHttpError(RequestException $e) { $this->fail(sprintf(<<<'EOL' failed to create user: HTTP ERROR %s EOL , $e->getMessage())); }
protected function handleError(RequestException $e) { $response = $e->getResponse(); switch ($response->getStatusCode()) { case 404: throw new Exceptions\NotFoundException($this->getResponseError($response)); default: throw new Exceptions\MeshException($this->getResponseError($response)); } }
/** * throwRequestException * * @param \GuzzleHttp\Exception\RequestException $e * @param string $className * @throws Exceptions\RequestException */ protected function throwRequestException($e, $className) { $response = $e->getResponse(); $rawBody = (string) $response->getBody(); $body = json_decode((string) $rawBody); $body = $body === null ? $rawBody : $body; $exception = new $className($e->getMessage(), $e->getCode()); $exception->setBody($body); throw $exception; }
public function __construct(RequestException $e, $message = '') { $prefix = $message ?: "Bad response from the WIU API"; if ($e->getCode()) { $prefix .= " (HTTP status {$e->getCode()})"; } $response = $e->getResponse(); $body = $response->json(); $message = isset($body['message']) ? $body['message'] : $response->getReasonPhrase(); parent::__construct("{$prefix}: {$message}", $e->getCode(), null); }
/** * @param GuzzleHttpRequestException $exception * @return Client\ClientException */ private static function createClientException(GuzzleHttpRequestException $exception) { $exceptionArray = array(400 => 'BadRequest', 401 => 'Unauthorized', 403 => 'Forbidden', 404 => 'NotFound', 405 => 'MethodNotAllowed', 406 => 'NotAcceptable'); foreach ($exceptionArray as $item => $value) { if ($item === $exception->getCode()) { $exceptionName = __NAMESPACE__ . '\\Client\\' . $value . 'Exception'; return new $exceptionName($exception); } } return new RequestException($exception); }
/** * Captch known exceptions * @param RequestException $e * @throws BolException * @throws \Exception */ public function handle(RequestException $e) { $response = $e->getResponse(); $statusCode = $response->getStatusCode(); $this->handleStatusCode($statusCode); $body = $response->getBody(true); $message = $this->xmlParser->parse($body); if (isset($message['ErrorCode'])) { throw new BolException($message['ErrorMessage'], $message['ErrorCode']); } throw new \Exception("Unknown error occurred. Status code: {$response->getStatusCode()}."); }
/** * Wraps an API exception in the appropriate domain exception. * * @param RequestException $e The API exception * * @return HttpException */ public static function wrap(RequestException $e) { $response = $e->getResponse(); if ($errors = self::errors($response)) { $class = self::exceptionClass($response, $errors[0]); $message = implode(', ', array_map('strval', $errors)); } else { $class = self::exceptionClass($response); $message = $e->getMessage(); } return new $class($message, $errors, $e->getRequest(), $response, $e); }
/** * @param RequestException $exception * * @return ApnsException */ private static function factoryException(RequestException $exception) { $response = $exception->getResponse(); if (null === $response) { return new ApnsException('Unknown network error', 0, $exception); } try { $contents = $response->getBody()->getContents(); } catch (\Exception $e) { return new ApnsException('Unknown network error', 0, $e); } return ExceptionFactory::factoryException($response->getStatusCode(), $contents, $exception); }
public function testHasThrowState() { $e = RequestException::create(new Request('GET', '/'), new Response(442)); $this->assertFalse($e->getThrowImmediately()); $e->setThrowImmediately(true); $this->assertTrue($e->getThrowImmediately()); }
/** * Throw a RequestException if the response is not marked as successful. * * @param \GuzzleHttp\Event\CompleteEvent $event * * @throws \GuzzleHttp\Exception\RequestException * * @return void */ public function onComplete(CompleteEvent $event) { $json = $event->getResponse()->json(); if (array_get($json, 'result') !== 'success' || array_key_exists('response', $json) === false) { throw RequestException::create($event->getRequest(), $event->getResponse()); } }
/** * Create the request exception. * * @param Request $request * @param RequestException|null $previousException * * @throws HttpRequestException */ protected function handleRequestException(Request $request, RequestException $previousException) { if (null !== $previousException && null == $previousException->getResponse()) { throw new NullResponseException($this->request, $previousException); } throw $this->createApiException($request, $this->createResponse($previousException->getResponse()), $previousException); }
public function testWrapsConnectExceptions() { $e = new ConnectException('foo'); $r = new Request('GET', 'http://www.oo.com'); $ex = RequestException::wrapException($r, $e); $this->assertInstanceOf('GuzzleHttp\\Exception\\ConnectException', $ex); }
public function __construct(RequestException $e) { $response = $e->getResponse(); $message = $response->getReasonPhrase(); $level = floor($response->getStatusCode() / 100); // Check if business-level error message // https://developer.zendesk.com/rest_api/docs/core/introduction#requests if ($response->getHeaderLine('Content-Type') == 'application/json; charset=UTF-8') { $responseBody = json_decode($response->getBody()->getContents()); $this->errorDetails = $responseBody->details; $message = $responseBody->description . "\n" . 'Errors: ' . print_r($this->errorDetails, true); } elseif ($level == '5') { $message = 'Zendesk may be experiencing internal issues or undergoing scheduled maintenance.'; } parent::__construct($message, $response->getStatusCode()); }
/** * @param string $message Exception message * @param CommandTransaction $trans Contextual transfer information * @param \Exception $previous Previous exception (if any) */ public function __construct($message, CommandTransaction $trans, \Exception $previous = null) { $this->trans = $trans; $request = $trans->request ?: new Request(null, null); $response = $trans->response; parent::__construct($message, $request, $response, $previous); }
/** * Sends an HTTP request. * * @param RequestInterface $request Request to send. * @param array $options Request transfer options. * * @return PromiseInterface */ public function __invoke(RequestInterface $request, array $options) { // Sleep if there is a delay specified. if (isset($options['delay'])) { usleep($options['delay'] * 1000); } $startTime = isset($options['on_stats']) ? microtime(true) : null; try { // Does not support the expect header. $request = $request->withoutHeader('Expect'); // Append a content-length header if body size is zero to match // cURL's behavior. if (0 === $request->getBody()->getSize()) { $request = $request->withHeader('Content-Length', 0); } return $this->createResponse($request, $options, $this->createStream($request, $options), $startTime); } catch (\InvalidArgumentException $e) { throw $e; } catch (\Exception $e) { // Determine if the error was a networking error. $message = $e->getMessage(); // This list can probably get more comprehensive. if (strpos($message, 'getaddrinfo') || strpos($message, 'Connection refused') || strpos($message, "couldn't connect to host")) { $e = new ConnectException($e->getMessage(), $request, $e); } $e = RequestException::wrapException($request, $e); $this->invokeStats($options, $request, $startTime, null, $e); return new RejectedPromise($e); } }
public function __construct(RequestException $e) { $response = $e->getResponse(); $message = $response->getReasonPhrase() . " [status code] " . $response->getStatusCode(); $level = floor($response->getStatusCode() / 100); // Check if business-level error message // https://developer.zendesk.com/rest_api/docs/core/introduction#requests if ($level == '4') { $responseBody = $response->getBody()->getContents(); $this->errorDetails = $responseBody; $message .= ' [details] ' . $this->errorDetails; } elseif ($level == '5') { $message .= ' [details] Zendesk may be experiencing internal issues or undergoing scheduled maintenance.'; } parent::__construct($message, $response->getStatusCode()); }
/** * Throw a RequestException on an HTTP protocol error * * @param CompleteEvent $event Emitted event * @throws RequestException */ public function onComplete(CompleteEvent $event) { $code = (string) $event->getResponse()->getStatusCode(); // Throw an exception for an unsuccessful response if ($code[0] === '4' || $code[0] === '5') { throw RequestException::create($event->getRequest(), $event->getResponse()); } }
/** * Converts a Guzzle exception into an Httplug exception. * * @param RequestException $exception * * @return Exception */ private function createException(RequestException $exception) { if ($exception->hasResponse()) { return new HttpException($exception->getMessage(), $exception->getRequest(), $exception->getResponse(), $exception); } return new NetworkException($exception->getMessage(), $exception->getRequest(), $exception); }
/** * @test * @expectedException \Jsor\HalClient\Exception\BadResponseException */ public function it_will_transform_exception_with_404_response() { $guzzleClient = $this->getMock('GuzzleHttp\\ClientInterface'); $guzzleClient->expects($this->once())->method('send')->will($this->returnCallback(function ($request) { throw GuzzleRequestException::create($request, new Response(404)); })); $client = new HalClient('http://propilex.herokuapp.com', new Guzzle6HttpClient($guzzleClient)); $client->request('GET', '/'); }
/** * @test * @expectedException \GuzzleHttp\Exception\RequestException */ public function magicCallResponseNotReceived() { $this->deferredHttpBinding = new FulfilledPromise($this->httpBindingMock); $this->httpBindingMock->method('request')->willReturn(new Request('POST', 'www.endpoint.com'))->with('someSoapMethod', [['some-key' => 'some-value']]); $this->httpBindingMock->expects($this->never())->method('response'); $this->handlerMock->append(GuzzleRequestException::create(new Request('POST', 'www.endpoint.com'))); $client = new SoapClient($this->clientMock, $this->deferredHttpBinding); $client->someSoapMethod(['some-key' => 'some-value'])->wait(); }
public function testBuild() { $request = new Request('GET', '/'); $this->assertInstanceOf('\\keika299\\ConohaAPI\\Common\\Exceptions\\Network\\Client\\BadRequestException', ExceptionFactory::build(RequestException::create($request, new Response('400')))); $this->assertInstanceOf('\\keika299\\ConohaAPI\\Common\\Exceptions\\Network\\Client\\UnauthorizedException', ExceptionFactory::build(RequestException::create($request, new Response('401')))); $this->assertInstanceOf('\\keika299\\ConohaAPI\\Common\\Exceptions\\Network\\Client\\ForbiddenException', ExceptionFactory::build(RequestException::create($request, new Response('403')))); $this->assertInstanceOf('\\keika299\\ConohaAPI\\Common\\Exceptions\\Network\\Client\\NotFoundException', ExceptionFactory::build(RequestException::create($request, new Response('404')))); $this->assertInstanceOf('\\keika299\\ConohaAPI\\Common\\Exceptions\\Network\\Client\\MethodNotAllowedException', ExceptionFactory::build(RequestException::create($request, new Response('405')))); $this->assertInstanceOf('\\keika299\\ConohaAPI\\Common\\Exceptions\\Network\\Client\\NotAcceptableException', ExceptionFactory::build(RequestException::create($request, new Response('406')))); $this->assertInstanceOf('\\keika299\\ConohaAPI\\Common\\Exceptions\\Network\\RequestException', ExceptionFactory::build(RequestException::create($request, new Response('499')))); }
public function __construct($message = null, $code = 0, Exception $previous = null) { switch ($code) { case 401: $message = 'Invalid token.'; break; case 400: $message = 'Identifier not found or invalid email/email_lead data.'; break; } parent::__construct($message, $code, $previous); }
/** * Gives human readable error message * @param RequestException $requestException * @return string */ protected function getPrettyErrorMessage(RequestException $requestException) { if (!$requestException->hasResponse()) { throw $requestException; } $errorMessage = ''; $response = json_decode($requestException->getResponse()->getBody()->getContents(), true); if (isset($response['message'])) { $errorMessage .= $response['message']; $errorMessage .= $this->getDetailedErrorMessage($response); } if (isset($response['error_description'])) { $errorMessage .= $response['error_description']; } if (isset($response['error'])) { $errorMessage .= ' [' . $response['error'] . ']'; } if (isset($response['code'])) { $errorMessage .= ' code: ' . $response['code']; } return $errorMessage; }
public function __construct(RequestException $e) { $this->request = $e->getRequest(); $this->response = $e->getResponse(); $simpleMessage = $e->getMessage(); $code = 0; if ($this->response) { try { $decodedJson = Utils::jsonDecode((string) $this->response->getBody(), true); if ($decodedJson && isset($decodedJson['errorType'])) { $simpleMessage = $decodedJson['errorType'] . ' ' . $decodedJson['message']; } } catch (\InvalidArgumentException $e) { // Not Json } $code = $this->response->getStatusCode(); } $responseDescription = $this->response ? (string) $this->response : 'none'; $requestDescription = $this->request ? (string) $this->request : 'none'; $message = sprintf("%s\n\nRequest: %s\n\nResponse: %s\n\n", $simpleMessage, $requestDescription, $responseDescription); parent::__construct($message, $code, $e); }
/** * Handles a Request Exception. * * @param RequestException $e The request exception. * * @return void */ protected function onRequestException(RequestException $e) { $request = $e->getRequest(); $response = $e->getResponse(); $statusCode = $response->getStatusCode(); $isClientError = $response->isClientError(); $isServerError = $response->isServerError(); if ($isClientError || $isServerError) { $content = $response->getContent(); $error = $response->getError(); $description = $response->getErrorDescription(); if (400 === $statusCode) { throw new BadRequestException($description, $error, $statusCode, $response, $request); } if (401 === $statusCode) { $otp = (string) $response->getHeader('X-Bitreserve-OTP'); if ('required' === $otp) { $description = 'Two factor authentication is enabled on this account'; throw new TwoFactorAuthenticationRequiredException($description, $error, $statusCode, $response, $request); } throw new AuthenticationRequiredException($description, $error, $statusCode, $response, $request); } if (404 === $statusCode) { $description = sprintf('Object or route not found: %s', $request->getPath()); throw new NotFoundException($description, 'not_found', $statusCode, $response, $request); } if (429 === $statusCode) { $rateLimit = $response->getApiRateLimit(); $description = sprintf('You have reached Bitreserve API limit. API limit is: %s. Your remaining requests will be reset at %s.', $rateLimit['limit'], date('Y-m-d H:i:s', $rateLimit['reset'])); throw new ApiLimitExceedException($description, $error, $statusCode, $response, $request); } throw new RuntimeException($description, $error, $statusCode, $response, $request); } }