Skip to content
This repository was archived by the owner on May 6, 2025. It is now read-only.

Commit 0fa7f20

Browse files
committed
Add error management for empty response
1 parent 62090b5 commit 0fa7f20

File tree

1 file changed

+22
-10
lines changed

1 file changed

+22
-10
lines changed

src/Controller/StatisticsController.php

Lines changed: 22 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,11 @@
66
use Symfony\Component\HttpFoundation\Request;
77
use Symfony\Component\HttpFoundation\Response;
88
use Symfony\Component\Routing\Annotation\Route;
9+
use Symfony\Contracts\HttpClient\Exception\ClientExceptionInterface;
10+
use Symfony\Contracts\HttpClient\Exception\DecodingExceptionInterface;
11+
use Symfony\Contracts\HttpClient\Exception\RedirectionExceptionInterface;
12+
use Symfony\Contracts\HttpClient\Exception\ServerExceptionInterface;
13+
use Symfony\Contracts\HttpClient\Exception\TransportExceptionInterface;
914
use Symfony\Contracts\HttpClient\HttpClientInterface;
1015
use Symfony\UX\Chartjs\Builder\ChartBuilderInterface;
1116
use Symfony\UX\Chartjs\Model\Chart;
@@ -77,6 +82,9 @@ public function __invoke(Request $request): Response
7782

7883
private function transformFollowerStats(array $elasticStats): array
7984
{
85+
if (!isset($elasticStats['aggregations']) || count($elasticStats['aggregations']) <= 0) {
86+
return [];
87+
}
8088
$latestData = end($elasticStats['aggregations'][0]['buckets']);
8189

8290
$stats = ['total_followers' => 0];
@@ -126,14 +134,15 @@ private function transformFollowerStats(array $elasticStats): array
126134
return $stats;
127135
}
128136

129-
private function getStatsFromElastic(): array
137+
private function getStatsFromElastic(): ?array
130138
{
131-
$response = $this->elasticsearchClient->request('GET', '/*user_stats/_search', [
132-
'headers' => [
133-
'Content-Type' => 'application/json',
134-
'Accept' => 'application/json',
135-
],
136-
'body' => '
139+
try {
140+
$response = $this->elasticsearchClient->request('GET', '/*user_stats/_search', [
141+
'headers' => [
142+
'Content-Type' => 'application/json',
143+
'Accept' => 'application/json',
144+
],
145+
'body' => '
137146
{
138147
"aggs": {
139148
"0": {
@@ -194,7 +203,7 @@ private function getStatsFromElastic(): array
194203
"should": [
195204
{
196205
"match": {
197-
"userId": ' . $this->getUser()->getId() . '
206+
"userId": '.$this->getUser()->getId().'
198207
}
199208
}
200209
],
@@ -219,8 +228,11 @@ private function getStatsFromElastic(): array
219228
}
220229
}
221230
}',
222-
]);
231+
]);
223232

224-
return $response->toArray();
233+
return $response->toArray();
234+
} catch (ClientExceptionInterface|DecodingExceptionInterface|RedirectionExceptionInterface|ServerExceptionInterface|TransportExceptionInterface $e) {
235+
return null;
236+
}
225237
}
226238
}

0 commit comments

Comments
 (0)