Skip to content
This repository was archived by the owner on Sep 2, 2025. It is now read-only.

Commit c9f25d1

Browse files
authored
Merge pull request #137 from Yoshi2889/fix/better-exceptions
Decode Telegram response from ReactPHP's ResponseException
2 parents e4fdf5f + faeb241 commit c9f25d1

File tree

2 files changed

+34
-0
lines changed

2 files changed

+34
-0
lines changed

src/Exceptions/ClientException.php

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44

55
namespace unreal4u\TelegramAPI\Exceptions;
66

7+
use React\Http\Message\ResponseException;
78
use Throwable;
89
use unreal4u\TelegramAPI\Telegram\Types\Custom\UnsuccessfulRequest;
910

@@ -29,6 +30,34 @@ public function __construct(string $message = '', int $code = 0, Throwable $prev
2930
}
3031
}
3132

33+
/**
34+
* Construct a new ClientException with the parameters and, if present, body
35+
* found in the given ResponseException.
36+
*
37+
* @param \React\Http\Message\ResponseException $responseException
38+
*
39+
* @return static
40+
*/
41+
public static function fromResponseException(ResponseException $responseException): self {
42+
$exception = new ClientException(
43+
$responseException->getMessage(),
44+
$responseException->getCode(),
45+
$responseException
46+
);
47+
48+
$body = $responseException->getResponse()->getBody()->getContents();
49+
$decoded = json_decode($body, true);
50+
51+
if (is_array($decoded)
52+
&& array_key_exists('description', $decoded)
53+
&& array_key_exists('error_code', $decoded)
54+
) {
55+
$exception->setError(new UnsuccessfulRequest($decoded));
56+
}
57+
58+
return $exception;
59+
}
60+
3261
public function setError(UnsuccessfulRequest $unsuccessfulRequest): ClientException
3362
{
3463
$this->errorRequest = $unsuccessfulRequest;

src/HttpClientRequestHandler.php

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88
use Psr\Http\Message\ResponseInterface;
99
use React\EventLoop\LoopInterface;
1010
use React\Http\Browser;
11+
use React\Http\Message\ResponseException;
1112
use React\Promise\PromiseInterface;
1213
use React\Socket\Connector;
1314
use unreal4u\TelegramAPI\Exceptions\ClientException;
@@ -91,6 +92,10 @@ static function (ResponseInterface $response) {
9192
},
9293
// Promise rejected
9394
static function (Exception $e) {
95+
if ($e instanceof ResponseException) {
96+
throw ClientException::fromResponseException($e);
97+
}
98+
9499
throw new ClientException($e->getMessage(), $e->getCode(), $e);
95100
}
96101
);

0 commit comments

Comments
 (0)