Skip to content

Commit 3d22b82

Browse files
committed
[exceptions] add our own HttpException
1 parent a857ad1 commit 3d22b82

File tree

2 files changed

+72
-1
lines changed

2 files changed

+72
-1
lines changed

src/Client.php

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44

55
use AndroidSmsGateway\Domain\Message;
66
use AndroidSmsGateway\Domain\MessageState;
7-
use Http\Client\Exception\HttpException;
7+
use AndroidSmsGateway\Exceptions\HttpException;
88
use Http\Discovery\Psr17FactoryDiscovery;
99
use Http\Discovery\Psr18ClientDiscovery;
1010
use Psr\Http\Client\ClientInterface;

src/Exceptions/HttpException.php

Lines changed: 71 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,71 @@
1+
<?php
2+
3+
namespace AndroidSmsGateway\Exceptions;
4+
5+
use Psr\Http\Client\RequestExceptionInterface;
6+
use Psr\Http\Message\RequestInterface;
7+
use Psr\Http\Message\ResponseInterface;
8+
9+
final class HttpException extends \RuntimeException implements RequestExceptionInterface {
10+
/**
11+
* @var ResponseInterface
12+
*/
13+
protected $response;
14+
15+
/**
16+
* @var RequestInterface
17+
*/
18+
protected $request;
19+
20+
/**
21+
* @param string $message
22+
*/
23+
public function __construct(
24+
$message,
25+
RequestInterface $request,
26+
ResponseInterface $response,
27+
\Exception $previous = null
28+
) {
29+
parent::__construct($message, 0, $previous);
30+
31+
$this->request = $request;
32+
$this->response = $response;
33+
34+
$this->code = $response->getStatusCode();
35+
}
36+
37+
/**
38+
* {@inheritdoc}
39+
*/
40+
public function getRequest(): RequestInterface {
41+
return $this->request;
42+
}
43+
44+
/**
45+
* Returns the response.
46+
*
47+
* @return ResponseInterface
48+
*/
49+
public function getResponse() {
50+
return $this->response;
51+
}
52+
53+
/**
54+
* Factory method to create a new exception with a normalized error message.
55+
*/
56+
public static function create(
57+
RequestInterface $request,
58+
ResponseInterface $response,
59+
\Exception $previous = null
60+
): self {
61+
$message = sprintf(
62+
'[url] %s [http method] %s [status code] %s [reason phrase] %s',
63+
$request->getRequestTarget(),
64+
$request->getMethod(),
65+
$response->getStatusCode(),
66+
$response->getReasonPhrase()
67+
);
68+
69+
return new static($message, $request, $response, $previous);
70+
}
71+
}

0 commit comments

Comments
 (0)