diff --git a/src/Exceptions/LeverClientException.php b/src/Exceptions/LeverClientException.php new file mode 100644 index 0000000..7550548 --- /dev/null +++ b/src/Exceptions/LeverClientException.php @@ -0,0 +1,13 @@ +sendRequest('GET', $this->endpoint, $this->options); } catch (ClientException $e) { - throw $e; + $this->handleException($e, __METHOD__); + } catch (Exception $e) { + $this->handleException($e, __METHOD__); } finally { $this->reset(); } @@ -85,7 +90,9 @@ public function post(array $body = []): ResponseInterface try { return $this->sendRequest('POST', $this->endpoint, $this->prepareOptions($body)); } catch (ClientException $e) { - throw $e; + $this->handleException($e, __METHOD__, $body); + } catch (Exception $e) { + $this->handleException($e, __METHOD__, $body); } finally { $this->reset(); } @@ -96,7 +103,9 @@ public function put(array $body = []): ResponseInterface try { return $this->sendRequest('PUT', $this->endpoint, $this->prepareOptions($body)); } catch (ClientException $e) { - throw $e; + $this->handleException($e, __METHOD__, $body); + } catch (Exception $e) { + $this->handleException($e, __METHOD__, $body); } finally { $this->reset(); } @@ -476,4 +485,27 @@ private function checkExpandOptions(array|string $expand): bool return true; } + + private function handleException(\Exception $e, string $method, array $body = []): void + { + $logDetails = [ + 'package' => 'Bluelightco\LeverPhp', + 'method' => $method, + 'endpoint' => $this->endpoint, + ]; + + if (! empty($body)) { + $logDetails['body'] = json_encode($body); + } + + if ($e instanceof ClientException) { + $logDetails['response'] = $e->getResponse() ? $e->getResponse()->getBody()->getContents() : null; + } + + Log::error("HTTP Error in $method: " . $e->getMessage(), $logDetails); + + $type = $e instanceof ClientException ? 'ClientException' : 'Exception'; + + throw new LeverClientException("$type error executing HTTP request in $method. Please check the logs for more details."); + } } diff --git a/tests/OpportunitiesTest.php b/tests/OpportunitiesTest.php index 09dd641..b90df30 100644 --- a/tests/OpportunitiesTest.php +++ b/tests/OpportunitiesTest.php @@ -2,9 +2,9 @@ namespace Bluelightco\LeverPhp\Tests; -use GuzzleHttp\Exception\ClientException; use GuzzleHttp\Psr7\Response; use Illuminate\Support\LazyCollection; +use Bluelightco\LeverPhp\Exceptions\LeverClientException; class OpportunitiesTest extends TestCase { @@ -108,7 +108,7 @@ public function create_opportunity() /** @test */ public function fail_to_create_opportunity_when_no_perform_as_parameter_included() { - $this->expectException(ClientException::class); + $this->expectException(LeverClientException::class); $this->mockHandler->append(new Response(400, [], '{"code": "BadRequestError", "message": "Missing perform_as parameter. Please specify a user for which to perform this create."}'