Skip to content

Commit 083753a

Browse files
improve logging of fetch error (#12)
1 parent 38779f7 commit 083753a

2 files changed

Lines changed: 29 additions & 5 deletions

File tree

src/lib/client.ts

Lines changed: 28 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -3,13 +3,37 @@ import { getCompetitionStatus } from '@/lib/manager';
33
import config from '@/lib/config';
44

55
export async function getCompetitionsWithStatus(): Promise<CompetitionWithStatus[]> {
6-
const res = await fetch(config.competitionsMetadataUrl);
6+
const url = config.competitionsMetadataUrl;
7+
const res = await fetchWithDetailedErrors(url);
8+
const payload = await parseJsonWithDetailedErrors(res, url);
9+
10+
const competitions = (payload as { competitions: Competition[] }).competitions;
11+
12+
return Promise.all(competitions.map((competition) => getCompetitionStatus(competition)));
13+
}
14+
15+
async function fetchWithDetailedErrors(url: string): Promise<Response> {
16+
let res: Response;
17+
try {
18+
res = await fetch(url);
19+
} catch (error) {
20+
const reason = error instanceof Error ? error.message : String(error);
21+
throw new Error(`Failed to fetch competitions metadata from ${url}: ${reason}`);
22+
}
723

824
if (!res.ok) {
9-
throw new Error('Failed to fetch data');
25+
const details = `HTTP ${res.status} ${res.statusText}`.trim();
26+
throw new Error(`Failed to fetch competitions metadata from ${url}: ${details}`);
1027
}
1128

12-
const competitions = (await res.json()).competitions as Competition[];
29+
return res;
30+
}
1331

14-
return Promise.all(competitions.map((competition) => getCompetitionStatus(competition)));
32+
async function parseJsonWithDetailedErrors(res: Response, url: string): Promise<unknown> {
33+
try {
34+
return await res.json();
35+
} catch (error) {
36+
const reason = error instanceof Error ? error.message : String(error);
37+
throw new Error(`Failed to parse competitions metadata JSON from ${url}: ${reason}`);
38+
}
1539
}

src/lib/config.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
import dotenv from 'dotenv';
22

3-
dotenv.config();
3+
dotenv.config({quiet: true});
44

55
const config = {
66
competitionsMetadataUrl:

0 commit comments

Comments
 (0)