From 4febdc6d20f9340da28d35e290863c67540384f9 Mon Sep 17 00:00:00 2001 From: javier-villatoro Date: Mon, 5 Aug 2024 19:01:56 -0600 Subject: [PATCH] Improve try catch flow for http requests --- src/Http/Client/LeverClient.php | 46 ++++++++++++--------------------- 1 file changed, 16 insertions(+), 30 deletions(-) diff --git a/src/Http/Client/LeverClient.php b/src/Http/Client/LeverClient.php index 3e8aefe..e1584be 100644 --- a/src/Http/Client/LeverClient.php +++ b/src/Http/Client/LeverClient.php @@ -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 @@ -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) {