Skip to content

Commit

Permalink
Improve try catch flow for http requests
Browse files Browse the repository at this point in the history
  • Loading branch information
javier-villatoro committed Aug 6, 2024
1 parent 89c716f commit 4febdc6
Showing 1 changed file with 16 additions and 30 deletions.
46 changes: 16 additions & 30 deletions src/Http/Client/LeverClient.php
Original file line number Diff line number Diff line change
Expand Up @@ -68,47 +68,31 @@ public function __construct(
// API requests

private function sendRequest($method, $endpoint, array $options = []): ResponseInterface
{
return $this->client->request($method, $endpoint, $options);
}

public function get(): ResponseInterface
{
try {
return $this->sendRequest('GET', $this->endpoint, $this->options);
return $this->client->request($method, $endpoint, $options);
} catch (ClientException $e) {
$this->handleException($e, __METHOD__);
$this->handleException($e, $method, $endpoint, $options);
} catch (Exception $e) {
$this->handleException($e, __METHOD__);
$this->handleException($e, $method, $endpoint, $options);
} finally {
$this->reset();
}
}

public function get(): ResponseInterface
{
return $this->sendRequest('GET', $this->endpoint, $this->options);
}

public function post(array $body = []): ResponseInterface
{
try {
return $this->sendRequest('POST', $this->endpoint, $this->prepareOptions($body));
} catch (ClientException $e) {
$this->handleException($e, __METHOD__, $body);
} catch (Exception $e) {
$this->handleException($e, __METHOD__, $body);
} finally {
$this->reset();
}
return $this->sendRequest('POST', $this->endpoint, $this->prepareOptions($body));
}

public function put(array $body = []): ResponseInterface
{
try {
return $this->sendRequest('PUT', $this->endpoint, $this->prepareOptions($body));
} catch (ClientException $e) {
$this->handleException($e, __METHOD__, $body);
} catch (Exception $e) {
$this->handleException($e, __METHOD__, $body);
} finally {
$this->reset();
}
return $this->sendRequest('PUT', $this->endpoint, $this->prepareOptions($body));
}

public function create(array $body, string $method = 'post'): array
Expand Down Expand Up @@ -486,16 +470,18 @@ private function checkExpandOptions(array|string $expand): bool
return true;
}

private function handleException(Exception $e, string $method, array $body = []): void
private function handleException(Exception $e, string $method, string $endpoint, array $options = []): void
{
$logDetails = [
'package' => 'Bluelightco\LeverPhp',
'method' => $method,
'endpoint' => $this->endpoint,
'endpoint' => $endpoint,
'options' => json_encode($options),
'response' => null,
];

if (! empty($body)) {
$logDetails['body'] = json_encode($body);
if (! empty($options)) {
$logDetails['options'] = json_encode($options);
}

if ($e instanceof ClientException) {
Expand Down

0 comments on commit 4febdc6

Please sign in to comment.