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

Commit 9571bbe

Browse files
author
Manuel Proß
committed
feat(web): add error handling to data fetch on homepage
1 parent a9b491d commit 9571bbe

File tree

1 file changed

+26
-4
lines changed

1 file changed

+26
-4
lines changed

web/src/app/api/[homepage]/route.ts

Lines changed: 26 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import { getNews } from "@/helpers/homepage";
22
import { SingleType } from "@/types/strapi";
3+
import { notFound, redirect } from "next/navigation";
34

45
export async function GET() {
56
const res = await fetch(`${process.env.CMS_API}/home?populate=deep`, {
@@ -9,18 +10,28 @@ export async function GET() {
910
});
1011

1112
if (!res.ok) {
13+
handleHTTPError(res.status);
1214
throw new Error("Fetching single type component home failed");
1315
}
1416

15-
const homePageData = (await res.json()) as SingleType;
17+
let homePageData: SingleType;
1618

17-
if (!homePageData.data.attributes.body) {
19+
try {
20+
homePageData = (await res.json()) as SingleType;
21+
} catch (e) {
22+
console.log(e);
23+
throw new Error("Failed to parse homepage data");
24+
}
25+
26+
if (!homePageData?.data.attributes.body) {
1827
return Response.json("Homepage contains no data");
1928
}
2029

2130
const newsSections = homePageData.data.attributes.body.flatMap((contentEntry, i) => {
22-
if ("newsCount" in contentEntry) return { index: i, newsCount: contentEntry.newsCount, headline: contentEntry.headline };
23-
else return [];
31+
if ("newsCount" in contentEntry) {
32+
return { index: i, newsCount: contentEntry.newsCount, headline: contentEntry.headline };
33+
}
34+
return [];
2435
});
2536

2637
for (const newsSectionEntry of newsSections) {
@@ -31,3 +42,14 @@ export async function GET() {
3142

3243
return Response.json(homePageData.data.attributes);
3344
}
45+
46+
function handleHTTPError(errorCode: number) {
47+
switch (errorCode) {
48+
case 400:
49+
return notFound();
50+
case 500:
51+
return redirect("/error/500");
52+
default:
53+
throw new Error("Fetching homepage data failed with status: " + errorCode);
54+
}
55+
}

0 commit comments

Comments
 (0)