Skip to content

Commit fcc0241

Browse files
authored
Merge pull request #456 from BoShurik/http-client-exception
Pass to HttpException correct description in custom http clients
2 parents f3b8d0b + d363950 commit fcc0241

File tree

2 files changed

+21
-2
lines changed

2 files changed

+21
-2
lines changed

src/Http/PsrHttpClient.php

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -85,7 +85,16 @@ protected function doRequest($url, array $data = null)
8585

8686
$content = $response->getBody()->getContents();
8787

88-
return self::jsonValidate($content);
88+
$json = self::jsonValidate($content);
89+
90+
if (!\in_array($response->getStatusCode(), [200, 304])) {
91+
$errorDescription = array_key_exists('description', $json) ? $json['description'] : $response->getReasonPhrase();
92+
$errorParameters = array_key_exists('parameters', $json) ? $json['parameters'] : [];
93+
94+
throw new HttpException($errorDescription, $response->getStatusCode(), null, $errorParameters);
95+
}
96+
97+
return $json;
8998
}
9099

91100
/**

src/Http/SymfonyHttpClient.php

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
use Symfony\Component\Mime\Part\DataPart;
66
use Symfony\Component\Mime\Part\Multipart\FormDataPart;
77
use Symfony\Contracts\HttpClient\Exception\ExceptionInterface;
8+
use Symfony\Contracts\HttpClient\Exception\HttpExceptionInterface;
89
use Symfony\Contracts\HttpClient\HttpClientInterface as SymfonyHttpClientInterface;
910
use TelegramBot\Api\HttpException;
1011

@@ -50,7 +51,16 @@ protected function doRequest($url, array $data = null)
5051
try {
5152
return $response->toArray();
5253
} catch (ExceptionInterface $exception) {
53-
throw new HttpException($exception->getMessage(), $exception->getCode(), $exception);
54+
if ($exception instanceof HttpExceptionInterface) {
55+
$response = $exception->getResponse()->toArray(false);
56+
$message = array_key_exists('description', $response) ? $response['description'] : $exception->getMessage();
57+
$parameters = array_key_exists('parameters', $response) ? $response['parameters'] : [];
58+
} else {
59+
$message = $exception->getMessage();
60+
$parameters = [];
61+
}
62+
63+
throw new HttpException($message, $exception->getCode(), $exception, $parameters);
5464
}
5565
}
5666

0 commit comments

Comments
 (0)