From f63ed1039b91d2d1049a1acbd7f85735acdfa68f Mon Sep 17 00:00:00 2001 From: David Villa Date: Thu, 16 Feb 2023 09:22:07 +0100 Subject: [PATCH] Improve error handling for API responses --- src/Services/Client.php | 37 +++++++++++++++++++++++++++++++++---- 1 file changed, 33 insertions(+), 4 deletions(-) diff --git a/src/Services/Client.php b/src/Services/Client.php index 0fffdec..076dea3 100644 --- a/src/Services/Client.php +++ b/src/Services/Client.php @@ -2,6 +2,7 @@ namespace KFoobar\Fortnox\Services; +use Illuminate\Http\Client\Response; use Illuminate\Support\Facades\Cache; use Illuminate\Support\Facades\Http; use KFoobar\Fortnox\Exceptions\FortnoxException; @@ -32,7 +33,13 @@ public function __construct() */ public function get(string $endpoint, array $data = [], array $filter = []): mixed { - return $this->client->get($endpoint, $data); + $response = $this->client->get($endpoint, $data); + + if ($response->failed()) { + $this->catchError($response); + } + + return $response; } /** @@ -48,7 +55,7 @@ public function put(string $endpoint, array $data = []): mixed $response = $this->client->put($endpoint, $data); if ($response->failed()) { - ray($response->json()); + $this->catchError($response); } return $response; @@ -68,7 +75,7 @@ public function post(string $endpoint, array $data = [], array $filter = []): mi $response = $this->client->post($endpoint, $data); if ($response->failed()) { - ray($response->json()); + $this->catchError($response); } return $response; @@ -87,12 +94,34 @@ public function delete(string $endpoint, array $data = []): mixed $response = $this->client->delete($endpoint, $data); if ($response->failed()) { - ray($response->json()); + $this->catchError($response); } return $response; } + /** + * Catch given error message from Fortnox. + * + * @param \Illuminate\Http\Client\Response $response + * + * @throws \KFoobar\Fortnox\Exceptions\FortnoxException (description) + * + * @return void + */ + protected function catchError(Response $response): void + { + if ($response->json('ErrorInformation')) { + throw new FortnoxException( + sprintf( + '%s (%s)', + $response->json('ErrorInformation.message'), + $response->json('ErrorInformation.code') + ) + ); + } + } + /** * Gets the host. *