7
7
use Http \Client \Common \Plugin ;
8
8
use Psr \Http \Message \RequestInterface ;
9
9
use Psr \Http \Message \ResponseInterface ;
10
+ use Symfony \Component \OptionsResolver \OptionsResolver ;
10
11
11
12
/**
12
13
* Throw exception when the response of a request is not acceptable.
17
18
*/
18
19
final class ErrorPlugin implements Plugin
19
20
{
21
+ /**
22
+ * @var bool Whether this plugin should only throw 5XX Exceptions (default to false).
23
+ *
24
+ * If set to true 4XX Responses code will never throw an exception
25
+ */
26
+ private $ onlyServerException ;
27
+
28
+ /**
29
+ * @param array $config {
30
+ *
31
+ * @var bool only_server_exception Whether this plugin should only throw 5XX Exceptions (default to false).
32
+ * }
33
+ */
34
+ public function __construct (array $ config = [])
35
+ {
36
+ $ resolver = new OptionsResolver ();
37
+ $ resolver ->setDefaults ([
38
+ 'only_server_exception ' => false ,
39
+ ]);
40
+ $ resolver ->setAllowedTypes ('only_server_exception ' , 'bool ' );
41
+ $ options = $ resolver ->resolve ($ config );
42
+
43
+ $ this ->onlyServerException = $ options ['only_server_exception ' ];
44
+ }
45
+
20
46
/**
21
47
* {@inheritdoc}
22
48
*/
@@ -42,7 +68,7 @@ public function handleRequest(RequestInterface $request, callable $next, callabl
42
68
*/
43
69
protected function transformResponseToException (RequestInterface $ request , ResponseInterface $ response )
44
70
{
45
- if ($ response ->getStatusCode () >= 400 && $ response ->getStatusCode () < 500 ) {
71
+ if (! $ this -> onlyServerException && $ response ->getStatusCode () >= 400 && $ response ->getStatusCode () < 500 ) {
46
72
throw new ClientErrorException ($ response ->getReasonPhrase (), $ request , $ response );
47
73
}
48
74
0 commit comments