diff --git a/CHANGELOG.md b/CHANGELOG.md index f64a7c0c..e4f40848 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +* Changed how errors are handled in Leantime api calls. * Modified getSprintReportData to work with Leantime data * Added project lead to client when syncing projects. * Remove description from create invoice page. diff --git a/src/Service/LeantimeApiService.php b/src/Service/LeantimeApiService.php index 5944e067..1356dbf0 100644 --- a/src/Service/LeantimeApiService.php +++ b/src/Service/LeantimeApiService.php @@ -3,6 +3,7 @@ namespace App\Service; use App\Exception\ApiServiceException; +use App\Exception\EconomicsException; use App\Interface\DataProviderServiceInterface; use App\Model\Invoices\PagedResult; use App\Model\Planning\Assignee; @@ -532,6 +533,7 @@ private function getIssuesForProjectMilestone($projectId, $milestoneId): array * Get from Leantime. * * @throws ApiServiceException + * @throws EconomicsException */ private function request(string $path, string $type, string $method, array $params = []): mixed { @@ -544,30 +546,21 @@ private function request(string $path, string $type, string $method, array $para 'params' => $params, ]] ); - $body = $response->getContent(false); - switch ($response->getStatusCode()) { - case 200: - if ($body) { - return json_decode($body, null, 512, JSON_THROW_ON_ERROR)->result; - } - break; - case 400: - case 401: - case 403: - case 409: - if ($body) { - $error = json_decode($body, null, 512, JSON_THROW_ON_ERROR); - if (!empty($error->errorMessages)) { - $msg = array_pop($error->errorMessages); - } else { - $msg = $error->errors->projectKey; - } - throw new ApiServiceException($msg); - } - break; + + $body = $response->getContent(); + + if ($body) { + $data = json_decode($body, null, 512, JSON_THROW_ON_ERROR); + + if (isset($data->error)) { + $message = $data->error->message; + throw new ApiServiceException($message, $data->error->code); + } + + return $data->result; } } catch (\Throwable $e) { - throw new ApiServiceException($e->getMessage(), (int) $e->getCode(), $e); + throw new ApiServiceException('Error from Leantime API: '.$e->getMessage(), (int) $e->getCode(), $e); } return null;