Skip to content

Commit

Permalink
Merge pull request #456 from BoShurik/http-client-exception
Browse files Browse the repository at this point in the history
Pass to HttpException correct description in custom http clients
  • Loading branch information
BoShurik authored Sep 29, 2023
2 parents f3b8d0b + d363950 commit fcc0241
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 2 deletions.
11 changes: 10 additions & 1 deletion src/Http/PsrHttpClient.php
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,16 @@ protected function doRequest($url, array $data = null)

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

return self::jsonValidate($content);
$json = self::jsonValidate($content);

if (!\in_array($response->getStatusCode(), [200, 304])) {
$errorDescription = array_key_exists('description', $json) ? $json['description'] : $response->getReasonPhrase();
$errorParameters = array_key_exists('parameters', $json) ? $json['parameters'] : [];

throw new HttpException($errorDescription, $response->getStatusCode(), null, $errorParameters);
}

return $json;
}

/**
Expand Down
12 changes: 11 additions & 1 deletion src/Http/SymfonyHttpClient.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
use Symfony\Component\Mime\Part\DataPart;
use Symfony\Component\Mime\Part\Multipart\FormDataPart;
use Symfony\Contracts\HttpClient\Exception\ExceptionInterface;
use Symfony\Contracts\HttpClient\Exception\HttpExceptionInterface;
use Symfony\Contracts\HttpClient\HttpClientInterface as SymfonyHttpClientInterface;
use TelegramBot\Api\HttpException;

Expand Down Expand Up @@ -50,7 +51,16 @@ protected function doRequest($url, array $data = null)
try {
return $response->toArray();
} catch (ExceptionInterface $exception) {
throw new HttpException($exception->getMessage(), $exception->getCode(), $exception);
if ($exception instanceof HttpExceptionInterface) {
$response = $exception->getResponse()->toArray(false);
$message = array_key_exists('description', $response) ? $response['description'] : $exception->getMessage();
$parameters = array_key_exists('parameters', $response) ? $response['parameters'] : [];
} else {
$message = $exception->getMessage();
$parameters = [];
}

throw new HttpException($message, $exception->getCode(), $exception, $parameters);
}
}

Expand Down

0 comments on commit fcc0241

Please sign in to comment.