Factory method to create a new exception with a normalized error message
public static create ( Psr\Http\Message\RequestInterface $request, Psr\Http\Message\ResponseInterface $response = null, Exception $previous = null, array $ctx = [] ) : self | ||
$request | Psr\Http\Message\RequestInterface | Request |
$response | Psr\Http\Message\ResponseInterface | Response received |
$previous | Exception | Previous exception |
$ctx | array | Optional handler context. |
Результат | self |
/** * 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()); } }
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 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()); } }
/** * @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(); }
/** * @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', '/'); }
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')))); }
/** * Middleware that throws exceptions for 4xx or 5xx responses when the * "http_error" request option is set to true. * * @return callable Returns a function that accepts the next handler. */ public static function httpErrors() { return function (callable $handler) { return function ($request, array $options) use($handler) { if (empty($options['http_errors'])) { return $handler($request, $options); } return $handler($request, $options)->then(function (ResponseInterface $response) use($request, $handler) { $code = $response->getStatusCode(); if ($code < 400) { return $response; } throw RequestException::create($request, $response); }); }; }; }
/** * {@inheritdoc} */ public static function create(HttpRequestInterface $request, HttpResponseInterface $response = null, Exception $previous = null, array $handlerContext = null) { if ($request instanceof RequestInterface && $response instanceof ResponseInterface) { static $clientErrorCodes = [-32600, -32601, -32602, -32700]; $errorCode = $response->getRpcErrorCode(); if (in_array($errorCode, $clientErrorCodes)) { $label = 'Client RPC error response'; $className = __NAMESPACE__ . '\\ClientException'; } else { $label = 'Server RPC error response'; $className = __NAMESPACE__ . '\\ServerException'; } $message = $label . ' [uri] ' . $request->getRequestTarget() . ' [method] ' . $request->getRpcMethod() . ' [error code] ' . $errorCode . ' [error message] ' . $response->getRpcErrorMessage(); return new $className($message, $request, $response, $previous); } return parent::create($request, $response, $previous); }
/** * @param RequestInterface $request * @param array $options * * @return PromiseInterface */ public function __invoke(RequestInterface $request, array $options) { $nextHandler = $this->nextHandler; if ($request->hasHeader('Authorization')) { return $nextHandler($request, $options); } $request = $request->withHeader('Authorization', sprintf('Bearer %s', $this->session->getToken())); return $nextHandler($request, $options)->then(function (ResponseInterface $response) use($request, $options) { $code = $response->getStatusCode(); if ($code < 400) { return $response; } if ($response->hasHeader("WWW-Authenticate")) { throw BearerErrorResponseException::create($request, $response); } throw RequestException::create($request, $response); }); }
/** * Use the send method to call every endpoint except for oauth/tokens * * @param HttpClient $client * @param string $endPoint E.g. "/tickets.json" * @param array $options * Available options are listed below: * array $queryParams Array of unencoded key-value pairs, e.g. ["ids" => "1,2,3,4"] * array $postFields Array of unencoded key-value pairs, e.g. ["filename" => "blah.png"] * string $method "GET", "POST", etc. Default is GET. * string $contentType Default is "application/json" * * @return \stdClass | null The response body, parsed from JSON into an object. Also returns null if something went wrong * @throws ApiResponseException * @throws AuthException */ public static function send(HttpClient $client, $endPoint, $options = []) { $options = array_merge(['method' => 'GET', 'contentType' => 'application/json', 'postFields' => null, 'queryParams' => null], $options); $headers = array_merge(['Accept' => 'application/json', 'Content-Type' => $options['contentType'], 'User-Agent' => $client->getUserAgent()], $client->getHeaders()); $request = new Request($options['method'], $client->getApiUrl() . $client->getApiBasePath() . $endPoint, $headers); $requestOptions = []; if (!empty($options['multipart'])) { $request = $request->withoutHeader('Content-Type'); $requestOptions['multipart'] = $options['multipart']; } elseif (!empty($options['postFields'])) { $request = $request->withBody(\GuzzleHttp\Psr7\stream_for(json_encode($options['postFields']))); } elseif (!empty($options['file'])) { if (is_file($options['file'])) { $fileStream = new LazyOpenStream($options['file'], 'r'); $request = $request->withBody($fileStream); } } if (!empty($options['queryParams'])) { foreach ($options['queryParams'] as $queryKey => $queryValue) { $uri = $request->getUri(); $uri = $uri->withQueryValue($uri, $queryKey, $queryValue); $request = $request->withUri($uri, true); } } // \RockstarGames\Cake\Log\Log::debug($request); // \RockstarGames\Cake\Log\Log::debug($options); try { list($request, $requestOptions) = $client->getAuth()->prepareRequest($request, $requestOptions); $response = $client->guzzle->send($request, $requestOptions); } catch (RequestException $e) { $requestException = RequestException::create($e->getRequest(), $e->getResponse()); throw new ApiResponseException($requestException); } finally { $client->setDebug($request->getHeaders(), $request->getBody()->getContents(), isset($response) ? $response->getStatusCode() : null, isset($response) ? $response->getHeaders() : null, isset($e) ? $e : null); $request->getBody()->rewind(); } if (isset($file)) { fclose($file); } $client->setSideload(null); return json_decode($response->getBody()->getContents()); }
/** * Test we can handle api exceptions when no response is returned from the API * * @expectedException Zendesk\API\Exceptions\ApiResponseException * @expectedExceptionMessage Error completing request */ public function testHandlesEmptyResponse() { // Create an exception object which is thrown when a response couldn't be retrieved $unsuccessfulResponse = RequestException::create(new Request('GET', 'foo'), null); $this->mockApiResponses($unsuccessfulResponse); $this->dummyResource->create(['foo' => 'bar']); }
public function testHasStatusCodeAsExceptionCode() { $e = RequestException::create(new Request('GET', '/'), new Response(442)); $this->assertEquals(442, $e->getCode()); }
/** * Check if a document exists. * * {@internal It would be nice to do a HEAD requests here, but APIs often don't support it}} * * @param string|array $id ID or filter * @param array $opts * @return boolean */ public static function exists($id, array $opts = []) { $filter = is_array($id) ? $id : static::idToFilter($id); $query = static::filterToQuery($filter); $opts['parse'] = false; $opts['http_errors'] = false; $method = static::getExistsMethod(); $response = static::getDB()->request($method, static::getUri(), compact('query') + $opts); $statusCode = $response->getStatusCode(); if ($statusCode >= 400 && $statusCode != 404) { $request = static::getDB()->createRequest($method, static::getUri(), $query); throw RequestException::create($request, $response); } return $statusCode < 300; // Any 2xx code }
/** * Handles all api calls * * @param string $uri * @param array $params * @return array * @throws \Exception */ public function getRequest($uri, array $params = []) { // validate uri if (!is_string($uri)) { throw new InvalidArgumentException("Invalid uri {$uri} submitted."); } // make sure uri isn't absolute - remove first / if there if ($uri[0] == '/') { $uri = substr($uri, 1); } try { $request = $this->client->createRequest('GET', $uri, ['query' => $params]); $response = $this->client->send($request)->json(); // cairo returns 200 even for errors so check response for error // errors array can have multiple, which do we show? create one string for all? if (!empty($response['errors'])) { throw RequestException::create($request, new Response($response['errors'][0]['code'], [], null, ['reason_phrase' => $response['errors'][0]['messages'][0]])); } } catch (RequestException $e) { $message = $e->getRequest() . "\n"; if ($e->hasResponse()) { $message .= $e->getResponse() . "\n"; } throw new Exception($message, $e->getCode()); } return $response; }