1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Http\Client\Plugin; |
4
|
|
|
|
5
|
1 |
|
@trigger_error('The '.__NAMESPACE__.'\ErrorPlugin class is deprecated since version 1.1 and will be removed in 2.0. Use Http\Client\Common\Plugin\ErrorPlugin instead.', E_USER_DEPRECATED); |
|
|
|
|
6
|
|
|
|
7
|
|
|
use Http\Client\Plugin\Exception\ClientErrorException; |
8
|
|
|
use Http\Client\Plugin\Exception\ServerErrorException; |
9
|
|
|
use Psr\Http\Message\RequestInterface; |
10
|
|
|
use Psr\Http\Message\ResponseInterface; |
11
|
|
|
|
12
|
|
|
/** |
13
|
|
|
* Throw exception when the response of a request is not acceptable. |
14
|
|
|
* |
15
|
|
|
* By default an exception will be thrown for all status codes from 400 to 599. |
16
|
|
|
* |
17
|
|
|
* @author Joel Wurtz <[email protected]> |
18
|
|
|
* |
19
|
|
|
* @deprecated since since version 1.1, and will be removed in 2.0. Use {@link \Http\Client\Common\Plugin\ErrorPlugin} instead. |
20
|
|
|
*/ |
21
|
|
|
class ErrorPlugin implements Plugin |
|
|
|
|
22
|
|
|
{ |
23
|
|
|
/** |
24
|
|
|
* {@inheritdoc} |
25
|
|
|
*/ |
26
|
3 |
|
public function handleRequest(RequestInterface $request, callable $next, callable $first) |
27
|
|
|
{ |
28
|
3 |
|
$promise = $next($request); |
29
|
|
|
|
30
|
3 |
|
return $promise->then(function (ResponseInterface $response) use ($request) { |
31
|
3 |
|
return $this->transformResponseToException($request, $response); |
32
|
3 |
|
}); |
33
|
|
|
} |
34
|
|
|
|
35
|
|
|
/** |
36
|
|
|
* Transform response to an error if possible. |
37
|
|
|
* |
38
|
|
|
* @param RequestInterface $request Request of the call |
39
|
|
|
* @param ResponseInterface $response Response of the call |
40
|
|
|
* |
41
|
|
|
* @throws ClientErrorException If response status code is a 4xx |
42
|
|
|
* @throws ServerErrorException If response status code is a 5xx |
43
|
|
|
* |
44
|
|
|
* @return ResponseInterface If status code is not in 4xx or 5xx return response |
45
|
|
|
*/ |
46
|
3 |
|
protected function transformResponseToException(RequestInterface $request, ResponseInterface $response) |
47
|
|
|
{ |
48
|
3 |
View Code Duplication |
if ($response->getStatusCode() >= 400 && $response->getStatusCode() < 500) { |
|
|
|
|
49
|
1 |
|
throw new ClientErrorException($response->getReasonPhrase(), $request, $response); |
|
|
|
|
50
|
|
|
} |
51
|
|
|
|
52
|
2 |
View Code Duplication |
if ($response->getStatusCode() >= 500 && $response->getStatusCode() < 600) { |
|
|
|
|
53
|
1 |
|
throw new ServerErrorException($response->getReasonPhrase(), $request, $response); |
|
|
|
|
54
|
|
|
} |
55
|
|
|
|
56
|
1 |
|
return $response; |
57
|
|
|
} |
58
|
|
|
} |
59
|
|
|
|
If you suppress an error, we recommend checking for the error condition explicitly: