Skip to content

Commit

Permalink
Improve response handling
Browse files Browse the repository at this point in the history
  • Loading branch information
Alex committed Jun 20, 2018
1 parent 0e779b4 commit f848b66
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 17 deletions.
31 changes: 15 additions & 16 deletions src/Api.php
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ class Api {

public function __construct(string $token, ClientInterface $client = null) {
$this->token = $token;
$this->client = is_null($client) ? new Client() : $client;
$this->client = $client;
}

public function getMe(): User {
Expand Down Expand Up @@ -213,21 +213,11 @@ public function request(string $method, array $params = [], $type = null, $isArr
$params['reply_markup'] = (string)$params['reply_markup'];
}

try {
$result = $this->client->request('POST', self::API_URL."/bot{$this->token}/{$method}", ['form_params' => $params]);
} catch (ClientException $e) {
if (strpos($e->getMessage(), 'response:') !== false) {
$ex = explode('response:', $e->getMessage());
$response = json_decode(trim(end($ex)));

if (empty($response)) {
throw new ResponseException($e->getMessage(), $e->getCode());
} else {
throw new ResponseException($response->description, $response->error_code);
}
} else {
throw $e;
}
$result = $this->getClient()->post(self::API_URL."/bot{$this->token}/{$method}", ['form_params' => $params]);
$data = json_decode($result->getBody(), true);

if (!$data['ok']) {
throw new ResponseException($data['description'], $data['error_code']);
}

$data = json_decode($result->getBody(), true);
Expand All @@ -239,6 +229,15 @@ public function request(string $method, array $params = [], $type = null, $isArr
} else {
return is_null($type) ? $data['result'] : new $type($data['result']);
}
}

protected function getClient(): ClientInterface {
if (empty($this->client)) {
$this->client = new Client([
'http_errors' => false
]);
}

return $this->client;
}
}
2 changes: 1 addition & 1 deletion tests/TestClient.php
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ protected function getMe(array $params) {

protected function getChat(array $params) {
if ($params['chat_id'] == -1) {
throw new ClientException('`400 Bad Request` response:{"ok":false,"error_code":400,"description":"Bad Request: chat not found"}', new Request('POST', '/'));
return '{"ok":false,"error_code":400,"description":"Bad Request: chat not found"}';
}
}

Expand Down

0 comments on commit f848b66

Please sign in to comment.