From 359de6e9f8d7ab1ae5db1f6a56d5f59f594cf220 Mon Sep 17 00:00:00 2001
From: catjoha04-byte
Date: Tue, 10 Nov 2026 19:33:32 +0100
Subject: [PATCH 1/8] feat: add error message when server can't be reached
---
Frontend/src/FrontendLogic/LogicConnection.ts | 24 ++++++++++++-------
Frontend/src/tests/WishlistPage.test.tsx | 4 ++--
2 files changed, 18 insertions(+), 10 deletions(-)
diff --git a/Frontend/src/FrontendLogic/LogicConnection.ts b/Frontend/src/FrontendLogic/LogicConnection.ts
index 0b50100..2ca0644 100644
--- a/Frontend/src/FrontendLogic/LogicConnection.ts
+++ b/Frontend/src/FrontendLogic/LogicConnection.ts
@@ -1,15 +1,23 @@
export const BACKEND_URL = import.meta.env.VITE_BACKEND_URL ?? 'http://it2810-10.idi.ntnu.no:3001/'
+export const NETWORK_ERROR_MESSAGE =
+ 'Could not reach the server. Check your connection and try again.'
+
export async function Gql(query: string, variables: Record): Promise {
const token = GetStoredToken()
- const res = await fetch(BACKEND_URL, {
- method: 'POST',
- headers: {
- 'Content-Type': 'application/json',
- ...(token ? { Authorization: `Bearer ${token}` } : {})
- },
- body: JSON.stringify({ query, variables })
- })
+ let res: Response
+ try {
+ res = await fetch(BACKEND_URL, {
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/json',
+ ...(token ? { Authorization: `Bearer ${token}` } : {})
+ },
+ body: JSON.stringify({ query, variables })
+ })
+ } catch {
+ throw new Error(NETWORK_ERROR_MESSAGE)
+ }
if (!res.ok) throw new Error(`Request failed: ${res.status}`)
const json = await res.json()
if (json.errors) throw new Error(json.errors[0].message)
diff --git a/Frontend/src/tests/WishlistPage.test.tsx b/Frontend/src/tests/WishlistPage.test.tsx
index 5e8dd41..9ed7c97 100644
--- a/Frontend/src/tests/WishlistPage.test.tsx
+++ b/Frontend/src/tests/WishlistPage.test.tsx
@@ -196,10 +196,10 @@ describe('wishlistLogicFrontend', () => {
await expect(FetchWishlistFrontend(1)).rejects.toThrow('first')
})
- it('passes network failures on to the caller', async () => {
+ it('turns network failures into a readable message', async () => {
FetchMock.mockRejectedValue(new TypeError('Failed to fetch'))
- await expect(FetchWishlistFrontend(1)).rejects.toThrow('Failed to fetch')
+ await expect(FetchWishlistFrontend(1)).rejects.toThrow('Could not reach the server')
})
})
})
From 116eb1a74f27aa28f83fcc8a5582f320d3d9ed53 Mon Sep 17 00:00:00 2001
From: catjoha04-byte
Date: Tue, 10 Nov 2026 19:34:55 +0100
Subject: [PATCH 2/8] fix: load errors inside section without duplicates
---
Frontend/src/components/GenreGamesSection.tsx | 10 +++-
Frontend/src/components/RecentReviews.tsx | 9 +++-
Frontend/src/components/Reviews.tsx | 8 +++-
Frontend/src/components/TopGames.tsx | 9 +++-
Frontend/src/css/GamePage.css | 5 ++
Frontend/src/css/MainPage.css | 14 ++++++
Frontend/src/pages/GamePage.tsx | 10 ++--
Frontend/src/pages/MainPage.tsx | 37 ++++++++------
Frontend/src/pages/ProfilePage.tsx | 48 ++++++++++++-------
Frontend/src/pages/WishlistPage.tsx | 9 ++--
Frontend/src/tests/MainPage.test.tsx | 16 +++++--
11 files changed, 124 insertions(+), 51 deletions(-)
diff --git a/Frontend/src/components/GenreGamesSection.tsx b/Frontend/src/components/GenreGamesSection.tsx
index 2350ddf..83d1417 100644
--- a/Frontend/src/components/GenreGamesSection.tsx
+++ b/Frontend/src/components/GenreGamesSection.tsx
@@ -38,6 +38,7 @@ type GenreGamesSectionProps = {
title: string
genres: string[]
genresLoading: boolean
+ genresError?: string | null
loadGames: (genre: string) => Promise
loadingText: string
emptyText: string
@@ -49,6 +50,7 @@ export function GenreGamesSection({
title,
genres,
genresLoading,
+ genresError = null,
loadGames,
loadingText,
emptyText,
@@ -157,9 +159,13 @@ export function GenreGamesSection({
{isLoading ? (
{loadingText}
+ ) : genresError ? (
+
+ Could not load genres: {genresError}
+
) : loadError ? (
-
- {loadError}
+
+ Could not load games: {loadError}
) : visibleGames.length > 0 ? (
visibleGames.map((game) =>
)
diff --git a/Frontend/src/components/RecentReviews.tsx b/Frontend/src/components/RecentReviews.tsx
index 0a84cd1..86cd6fd 100644
--- a/Frontend/src/components/RecentReviews.tsx
+++ b/Frontend/src/components/RecentReviews.tsx
@@ -12,9 +12,10 @@ import type { Review } from '../types/Review'
type RecentReviewsProps = {
reviews: Review[]
isLoading: boolean
+ error?: string | null
}
-export default function RecentReviews({ reviews, isLoading }: RecentReviewsProps) {
+export default function RecentReviews({ reviews, isLoading, error = null }: RecentReviewsProps) {
const recentReviewsRef = useRef
(null)
const isStackedLayout = useMediaQuery('(max-width: 56rem)')
const [visibleReviewCount, setVisibleReviewCount] = useState(0)
@@ -73,7 +74,11 @@ export default function RecentReviews({ reviews, isLoading }: RecentReviewsProps
{isLoading ? (
- Loading reviews...
+ Loading reviews...
+ ) : error ? (
+
+ Could not load recent reviews: {error}
+
) : (
)}
- {(error ?? loadError) && (
+ {error && (
- {error ?? loadError}
+ {error}
)}
@@ -142,6 +142,10 @@ export default function Reviews({
onDelete={HandleDelete}
/>
))
+ ) : loadError ? (
+
+ Could not load reviews: {loadError}
+
) : (
No reviews yet.
)}
diff --git a/Frontend/src/components/TopGames.tsx b/Frontend/src/components/TopGames.tsx
index e9903e7..379efec 100644
--- a/Frontend/src/components/TopGames.tsx
+++ b/Frontend/src/components/TopGames.tsx
@@ -5,9 +5,10 @@ import PassiveGameCard from './PassiveGameCard'
interface TopGamesProps {
loading: boolean
featuredGames: PageGame[]
+ error?: string | null
}
-export default function TopGames({ loading, featuredGames }: TopGamesProps) {
+export default function TopGames({ loading, featuredGames, error = null }: TopGamesProps) {
return (
@@ -15,7 +16,11 @@ export default function TopGames({ loading, featuredGames }: TopGamesProps) {
{loading ? (
- Loading games...
+ Loading games...
+ ) : error ? (
+
+ Could not load the top games: {error}
+
) : featuredGames.length === 0 ? (
No games found.
) : (
diff --git a/Frontend/src/css/GamePage.css b/Frontend/src/css/GamePage.css
index d0b4a67..5295edc 100644
--- a/Frontend/src/css/GamePage.css
+++ b/Frontend/src/css/GamePage.css
@@ -4,6 +4,11 @@
margin: 0 auto;
}
+.game-page-message {
+ margin: 2rem auto;
+ max-width: 40rem;
+}
+
@media (max-width: 43.75rem) {
.game-page {
width: min(calc(100% - 2rem), 32rem);
diff --git a/Frontend/src/css/MainPage.css b/Frontend/src/css/MainPage.css
index cde951e..cc8963a 100644
--- a/Frontend/src/css/MainPage.css
+++ b/Frontend/src/css/MainPage.css
@@ -177,6 +177,20 @@
gap: 1.25rem;
}
+.main-page-error {
+ margin: 0;
+ padding: 1rem;
+ border: 1px solid var(--primary-component-color);
+ border-radius: var(--border-radius);
+ background-color: var(--primary-background-color);
+}
+
+.genre-games-row .main-page-error {
+ grid-column: 1 / -1;
+ padding: 0.5rem;
+ border: 0;
+}
+
.genre-see-more {
display: flex;
justify-content: flex-end;
diff --git a/Frontend/src/pages/GamePage.tsx b/Frontend/src/pages/GamePage.tsx
index 4be295f..2cbffe4 100644
--- a/Frontend/src/pages/GamePage.tsx
+++ b/Frontend/src/pages/GamePage.tsx
@@ -69,9 +69,11 @@ export default function GamePage() {
/>
{isLoading ? (
-
Loading game...
+
Loading game...
) : error ? (
-
Error loading game: {error}
+
+ Something went wrong while loading this game: {error}
+
) : game ? (
) : (
-
Game not found.
+
+ We couldn't find that game. It may have been removed, or the link is wrong.
+
)}
diff --git a/Frontend/src/pages/MainPage.tsx b/Frontend/src/pages/MainPage.tsx
index a2f67fe..a89d960 100644
--- a/Frontend/src/pages/MainPage.tsx
+++ b/Frontend/src/pages/MainPage.tsx
@@ -23,21 +23,25 @@ export default function MainPage() {
const [genres, setGenres] = useState([])
const [isLoadingFeatured, setIsLoadingFeatured] = useState(true)
const [isLoadingGenres, setIsLoadingGenres] = useState(true)
- const [error, setError] = useState(null)
+ // One error per section, so each failure is shown inside the box it belongs to
+ const [featuredError, setFeaturedError] = useState(null)
+ const [genresError, setGenresError] = useState(null)
+ const [reviewsError, setReviewsError] = useState(null)
const [recentReviews, setRecentReviews] = useState([])
const [isLoadingReviews, setIsLoadingReviews] = useState(true)
useEffect(() => {
let cancelled = false
- const ReportError = (e: unknown, fallback: string) => {
- if (!cancelled) setError(e instanceof Error ? e.message : fallback)
- }
+ const ReportError =
+ (setError: (message: string) => void, fallback: string) => (e: unknown) => {
+ if (!cancelled) setError(e instanceof Error ? e.message : fallback)
+ }
LoadTop3Games()
.then((games) => {
if (!cancelled) setFeaturedGames(games.map(ToPageGame))
})
- .catch((e: unknown) => ReportError(e, 'Could not load top games'))
+ .catch(ReportError(setFeaturedError, 'Could not load top games'))
.finally(() => {
if (!cancelled) setIsLoadingFeatured(false)
})
@@ -46,7 +50,7 @@ export default function MainPage() {
.then((loaded) => {
if (!cancelled) setGenres([...loaded].sort())
})
- .catch((e: unknown) => ReportError(e, 'Could not load genres'))
+ .catch(ReportError(setGenresError, 'Could not load genres'))
.finally(() => {
if (!cancelled) setIsLoadingGenres(false)
})
@@ -55,7 +59,7 @@ export default function MainPage() {
.then((reviews) => {
if (!cancelled) setRecentReviews(reviews)
})
- .catch((e: unknown) => ReportError(e, 'Could not load reviews'))
+ .catch(ReportError(setReviewsError, 'Could not load reviews'))
.finally(() => {
if (!cancelled) setIsLoadingReviews(false)
})
@@ -101,12 +105,11 @@ export default function MainPage() {
- {error && (
-
- {error}
-
- )}
-
+
@@ -114,6 +117,7 @@ export default function MainPage() {
title="Top 10 Games by Genre"
genres={genres}
genresLoading={isLoadingGenres}
+ genresError={genresError}
loadGames={LoadTopGamesByGenre}
loadingText="Loading games..."
emptyText="No games found for this genre."
@@ -123,6 +127,7 @@ export default function MainPage() {
title="Discounts by Genre"
genres={genres}
genresLoading={isLoadingGenres}
+ genresError={genresError}
loadGames={LoadDiscountedGames}
loadingText="Loading discount games..."
emptyText="No discount games found for this genre."
@@ -131,7 +136,11 @@ export default function MainPage() {
/>
-
+
diff --git a/Frontend/src/pages/ProfilePage.tsx b/Frontend/src/pages/ProfilePage.tsx
index e7eeaae..8497eea 100644
--- a/Frontend/src/pages/ProfilePage.tsx
+++ b/Frontend/src/pages/ProfilePage.tsx
@@ -3,7 +3,7 @@ import Header from '../components/Header'
import '../css/ProfilePage.css'
import PageHeading from '../components/PageHeading'
import ProfileCard from '../components/ProfileCard.tsx'
-import { useEffect, useState } from 'react'
+import { useEffect, useState, type ReactNode } from 'react'
import { UseAuth } from '../context/AuthContext.tsx'
import {
FetchGameOptions,
@@ -16,6 +16,27 @@ import ProfileEditor from '../components/ProfileEditor.tsx'
import UserReviews from '../components/UserReviews.tsx'
import { Button, Card, CardContent } from '@mui/material'
+function ProfileMessageCard({
+ children,
+ isError = false
+}: {
+ children: ReactNode
+ isError?: boolean
+}) {
+ return (
+
+
+
+ {children}
+
+
+
+ )
+}
+
export default function ProfilePage() {
const { user } = UseAuth()
const userId = user?.id
@@ -23,7 +44,6 @@ export default function ProfilePage() {
const [profile, setProfile] = useState(null)
const [gameOptions, setGameOptions] = useState([])
const [error, setError] = useState(null)
- const [loading, setLoading] = useState(false)
const [isEditing, setIsEditing] = useState(false)
useEffect(() => {
@@ -42,8 +62,6 @@ export default function ProfilePage() {
} catch (err) {
if (!cancelled)
setError(err instanceof Error ? err.message : 'Something went wrong.')
- } finally {
- if (!cancelled) setLoading(false)
}
}
@@ -84,21 +102,17 @@ export default function ProfilePage() {
{!user ? (
-
-
-
- You need to log in to view your profile.
-
-
-
+
+ You need to log in to view your profile.
+
+ ) : error ? (
+
+ Could not load your profile: {error}
+
+ ) : !profile ? (
+ Loading your profileā¦
) : (
<>
- {loading && Loadingā¦
}
- {error && (
-
- Error: {error}
-
- )}
{profile &&
(isEditing ? (
<>
diff --git a/Frontend/src/pages/WishlistPage.tsx b/Frontend/src/pages/WishlistPage.tsx
index facecec..8778213 100644
--- a/Frontend/src/pages/WishlistPage.tsx
+++ b/Frontend/src/pages/WishlistPage.tsx
@@ -160,15 +160,14 @@ export default function WishlistPage() {
}}
/>
- {error && (
-
- Could not load games: {error}
-
- )}
{isLoading ? (
Loading games...
) : !user ? (
Sign in to see your wishlist
+ ) : error ? (
+
+ Could not load games: {error}
+
) : sortedGames.length === 0 ? (
No games found on your wishlist.
) : (
diff --git a/Frontend/src/tests/MainPage.test.tsx b/Frontend/src/tests/MainPage.test.tsx
index a96da76..238f539 100644
--- a/Frontend/src/tests/MainPage.test.tsx
+++ b/Frontend/src/tests/MainPage.test.tsx
@@ -373,8 +373,11 @@ describe('MainPage', () => {
RenderMainPage()
- expect((await screen.findByRole('alert')).textContent).toContain('Database unavailable')
- expect(screen.getByText('No games found.')).toBeTruthy()
+ const topGamesSection = SectionOf('Top 3 Games')
+ expect((await within(topGamesSection).findByRole('alert')).textContent).toContain(
+ 'Database unavailable'
+ )
+ expect(within(topGamesSection).queryByText('No games found.')).toBeNull()
})
it('uses a fallback message for non-Error fetch failures', async () => {
@@ -390,7 +393,10 @@ describe('MainPage', () => {
RenderMainPage()
- expect((await screen.findByRole('alert')).textContent).toContain('Genres unavailable')
+ const alerts = await screen.findAllByRole('alert')
+ expect(alerts).toHaveLength(2)
+ for (const alert of alerts) expect(alert.textContent).toContain('Genres unavailable')
+ expect(screen.queryByText('No games found for this genre.')).toBeNull()
expect((screen.getAllByLabelText('Choose a genre')[0] as HTMLSelectElement).disabled).toBe(
true
)
@@ -403,7 +409,9 @@ describe('MainPage', () => {
RenderMainPage()
const topGamesSection = SectionOf('Top 10 Games by Genre')
- expect((await within(topGamesSection).findByRole('alert')).textContent).toBe('Server down')
+ expect((await within(topGamesSection).findByRole('alert')).textContent).toBe(
+ 'Could not load games: Server down'
+ )
expect(within(topGamesSection).queryByText('No games found for this genre.')).toBeNull()
})
From 0bbb0d59fa9b93dba99e7643d402599924d27c2c Mon Sep 17 00:00:00 2001
From: catjoha04-byte
Date: Tue, 10 Nov 2026 19:36:10 +0100
Subject: [PATCH 3/8] fix: fix friend and card error placements
---
Frontend/src/components/ActiveGameCard.tsx | 6 +-
Frontend/src/components/WishlistGameCard.tsx | 7 +-
Frontend/src/css/ActiveGameCard.css | 10 +++
Frontend/src/css/FriendsPage.css | 33 +++++++++-
Frontend/src/css/Global.css | 7 ++
Frontend/src/css/WishlistGameCard.css | 8 +++
Frontend/src/pages/FriendsPage.tsx | 67 +++++++++++++-------
7 files changed, 111 insertions(+), 27 deletions(-)
diff --git a/Frontend/src/components/ActiveGameCard.tsx b/Frontend/src/components/ActiveGameCard.tsx
index e91546b..0a7a792 100644
--- a/Frontend/src/components/ActiveGameCard.tsx
+++ b/Frontend/src/components/ActiveGameCard.tsx
@@ -153,8 +153,12 @@ export default function ActiveGameCard({
{isWishlisted ? 'Remove from wishlist' : 'Add to wishlist'}
)}
- {error && {error}
}
+ {error && (
+
+ {error}
+
+ )}
diff --git a/Frontend/src/components/WishlistGameCard.tsx b/Frontend/src/components/WishlistGameCard.tsx
index 757e8b3..218b7cc 100644
--- a/Frontend/src/components/WishlistGameCard.tsx
+++ b/Frontend/src/components/WishlistGameCard.tsx
@@ -66,9 +66,14 @@ export default function WishlistGameCard({
/>
)}
{game.price.toFixed(2)} $
- {error && {error}
}
+ {error && (
+
+ {error}
+
+ )}
+
{!readOnly && (
- setFriendCode(event.target.value)}
- inputProps={{ 'aria-label': 'Friend ID' }}
- />
-
+
- Add
-
-
+ {
+ setFriendCode(event.target.value)
+ setAddError(null)
+ }}
+ inputProps={{
+ 'aria-label': 'Friend ID',
+ 'aria-invalid': addError ? true : undefined,
+ 'aria-describedby': addError ? 'addFriendError' : undefined
+ }}
+ />
+
+ Add
+
+
+ {addError && (
+
+ {addError}
+
+ )}
+
}
/>
{user && ownCode && (
@@ -278,7 +296,6 @@ export default function FriendPage() {
)}
- {addError && {addError}
}
{showOnlyStatus ? (
- {statusPanel}
+
+ {statusPanel}
+
) : (
From 14c91f54a7b61a63e8d6097f89887783bda36120 Mon Sep 17 00:00:00 2001
From: catjoha04-byte
Date: Tue, 10 Nov 2026 19:45:28 +0100
Subject: [PATCH 4/8] merge
From bc21e13278462ea4301ad91484e72ab51c683d55 Mon Sep 17 00:00:00 2001
From: catjoha04-byte
Date: Tue, 10 Nov 2026 20:01:32 +0100
Subject: [PATCH 5/8] fix: show loading errors without duplicate for search and
filter
---
.../src/components/SearchPageControls.tsx | 15 ++++++++
Frontend/src/components/SearchPageResults.tsx | 6 ++--
Frontend/src/css/SearchPage.css | 4 +++
Frontend/src/hooks/useSearchPageResults.ts | 21 ++++++++---
Frontend/src/pages/SearchPage.tsx | 3 +-
Frontend/src/tests/SearchPage.test.tsx | 36 +++++++++++++++++++
6 files changed, 78 insertions(+), 7 deletions(-)
diff --git a/Frontend/src/components/SearchPageControls.tsx b/Frontend/src/components/SearchPageControls.tsx
index 94189d9..df487ab 100644
--- a/Frontend/src/components/SearchPageControls.tsx
+++ b/Frontend/src/components/SearchPageControls.tsx
@@ -23,6 +23,7 @@ interface SearchPageControlsProps {
isFilterActive: boolean
onToggleFilters: () => void
genres: string[]
+ genresError?: string | null
activeFilters: string[]
onFilterChange: (event: SelectChangeEvent) => void
activeSorting: SortOption
@@ -42,6 +43,7 @@ export default function SearchPageControls({
isFilterActive,
onToggleFilters,
genres,
+ genresError = null,
activeFilters,
onFilterChange,
activeSorting,
@@ -107,6 +109,10 @@ export default function SearchPageControls({
value={activeFilters}
onChange={onFilterChange}
label="Filter by genre"
+ disabled={!!genresError}
+ inputProps={{
+ 'aria-describedby': genresError ? 'filterGenresError' : undefined
+ }}
renderValue={(selected) =>
selected.length <= 1
? selected.join('')
@@ -119,6 +125,15 @@ export default function SearchPageControls({
))}
+ {genresError && (
+
+ Could not load genres: {genresError}
+
+ )}
- {totalCount > 0 && (
+ {!error && totalCount > 0 && (
{totalCount} {totalCount === 1 ? 'game' : 'games'} found
@@ -74,7 +74,9 @@ export default function SearchPageResults({
)}
{isLoading && games.length === 0 &&
Loading games...
}
- {!isLoading && games.length === 0 &&
No games found.
}
+ {!error && !isLoading && games.length === 0 && (
+
No games found.
+ )}
{games.length > 0 &&
}
(null)
const [totalCount, setTotalCount] = useState(0)
const [availableGenres, setAvailableGenres] = useState([])
+ const [genresError, setGenresError] = useState(null)
+ const [countError, setCountError] = useState(null)
useEffect(() => {
- FetchGenres().then(setAvailableGenres).catch(console.error)
+ FetchGenres().then(setAvailableGenres).catch((err: unknown) =>
+ setGenresError(err instanceof Error ? err.message : 'Could not load genres')
+ )
}, [])
useEffect(() => {
let cancelled = false
GetTotalGameCount({ search, genres })
.then((count) => {
- if (!cancelled) setTotalCount(count)
+ if (!cancelled) {
+ setTotalCount(count)
+ setCountError(null)
+ }
+ })
+ .catch((err: unknown) => {
+ if (!cancelled) {
+ setTotalCount(0)
+ setCountError(err instanceof Error ? err.message : 'Could not count the games')
+ }
})
- .catch(console.error)
return () => {
cancelled = true
}
@@ -101,9 +113,10 @@ export function useSearchPageResults({ page, search, genres, sort }: SearchPageR
return {
genres: availableGenres,
+ genresError,
totalCount,
games: result?.games ?? NO_GAMES,
- error: isCurrent ? result.error : null,
+ error: (isCurrent ? result.error : null) ?? countError,
isLoading: !isCurrent
}
}
diff --git a/Frontend/src/pages/SearchPage.tsx b/Frontend/src/pages/SearchPage.tsx
index 4b95070..5a87fc6 100644
--- a/Frontend/src/pages/SearchPage.tsx
+++ b/Frontend/src/pages/SearchPage.tsx
@@ -45,7 +45,7 @@ export function SearchPage() {
const [isFilterActive, setIsFilterActive] = useState(GetFilterMenuOpenSearchpage)
const appliedFilters = isFilterActive && activeFilters.length > 0 ? activeFilters : NO_FILTERS
const appliedSorting = isFilterActive ? activeSorting : DEFAULT_SORT
- const { genres, totalCount, games, error, isLoading } = useSearchPageResults({
+ const { genres, genresError, totalCount, games, error, isLoading } = useSearchPageResults({
page,
search: searchQuery,
genres: appliedFilters,
@@ -126,6 +126,7 @@ export function SearchPage() {
isFilterActive={isFilterActive}
onToggleFilters={ToggleActive}
genres={genres}
+ genresError={genresError}
activeFilters={activeFilters}
onFilterChange={HandleFilterChange}
activeSorting={activeSorting}
diff --git a/Frontend/src/tests/SearchPage.test.tsx b/Frontend/src/tests/SearchPage.test.tsx
index ab56963..c8a84f7 100644
--- a/Frontend/src/tests/SearchPage.test.tsx
+++ b/Frontend/src/tests/SearchPage.test.tsx
@@ -254,6 +254,42 @@ describe('SearchPage', () => {
await waitFor(() => expect(screen.queryByText('Loading games...')).toBeNull())
})
+ it('shows only the error, not "No games found" or a game count, when loading fails', async () => {
+ FetchGamesFromDB.mockRejectedValue(new Error('Database unavailable'))
+
+ RenderSearchPage()
+
+ expect(await screen.findByRole('alert')).toBeTruthy()
+ expect(screen.queryByText('No games found.')).toBeNull()
+ expect(screen.queryByText(/games? found$/)).toBeNull()
+ })
+
+ it('shows an error instead of a wrong count when counting the games fails', async () => {
+ FetchGamesFromDB.mockResolvedValue([])
+ GetTotalGameCount.mockRejectedValue(new Error('Count unavailable'))
+
+ RenderSearchPage()
+
+ expect((await screen.findByRole('alert')).textContent).toBe(
+ 'Could not load games: Count unavailable'
+ )
+ expect(screen.queryByText('No games found.')).toBeNull()
+ })
+
+ it('explains under the genre menu when the genres fail to load', async () => {
+ FetchGamesFromDB.mockResolvedValue([])
+ FetchGenres.mockRejectedValue(new Error('Genres unavailable'))
+
+ RenderSearchPage()
+ OpenFilters()
+
+ expect((await screen.findByRole('alert')).textContent).toBe(
+ 'Could not load genres: Genres unavailable'
+ )
+ // The games themselves still load, so the results area is unaffected
+ expect(screen.getByText('No games found.')).toBeTruthy()
+ })
+
it('toggles the filter controls', async () => {
FetchGamesFromDB.mockResolvedValue([])
From b1bdbdf6ed468d2074c438f08e05258b2e5c6e0c Mon Sep 17 00:00:00 2001
From: catjoha04-byte
Date: Tue, 10 Nov 2026 20:02:19 +0100
Subject: [PATCH 6/8] fix: show readable error when cannot reach server
---
.../src/FrontendLogic/GameLogicFrontend.ts | 25 +++++++++++--------
Frontend/src/tests/GameLogicFrontend.test.ts | 6 +++++
2 files changed, 21 insertions(+), 10 deletions(-)
diff --git a/Frontend/src/FrontendLogic/GameLogicFrontend.ts b/Frontend/src/FrontendLogic/GameLogicFrontend.ts
index 0fd559c..a230ffc 100644
--- a/Frontend/src/FrontendLogic/GameLogicFrontend.ts
+++ b/Frontend/src/FrontendLogic/GameLogicFrontend.ts
@@ -1,5 +1,5 @@
import type { Game } from '../../../Backend/Steam'
-import { BACKEND_URL } from './LogicConnection'
+import { BACKEND_URL, NETWORK_ERROR_MESSAGE } from './LogicConnection'
import { OrNull, ReadStored, RemoveStored, WriteStored } from './Storage'
interface GraphQLResponse {
@@ -7,6 +7,14 @@ interface GraphQLResponse {
errors?: { message: string }[]
}
+async function FetchBackend(init: RequestInit): Promise {
+ try {
+ return await fetch(BACKEND_URL, init)
+ } catch {
+ throw new Error(NETWORK_ERROR_MESSAGE)
+ }
+}
+
const CACHE_TTL_MS = 12 * 60 * 60 * 1000
const GAMES_CACHE_PREFIX = `games:v2:${encodeURIComponent(BACKEND_URL)}:`
@@ -105,7 +113,7 @@ export async function GetGameById(appid: number): Promise {
const cachedGame = FindCachedGameById(appid)
if (cachedGame) return cachedGame
- const response = await fetch(BACKEND_URL, {
+ const response = await FetchBackend({
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
@@ -128,8 +136,7 @@ export async function GetGameById(appid: number): Promise {
})
if (!response.ok) {
- const body = await response.text()
- throw new Error(`Failed to fetch game: ${response.status} ${body}`)
+ throw new Error(`Failed to fetch game: ${response.status}`)
}
const { data, errors } = (await response.json()) as GraphQLResponse<{
@@ -151,7 +158,7 @@ async function FetchGamesFromDB(
const cachedGames = ReadCachedGames(cacheKey)
if (cachedGames) return cachedGames
- const response = await fetch(BACKEND_URL, {
+ const response = await FetchBackend({
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
@@ -180,8 +187,7 @@ async function FetchGamesFromDB(
})
if (!response.ok) {
- const body = await response.text()
- throw new Error(`Failed to fetch resources: ${response.status} ${body}`)
+ throw new Error(`Failed to fetch resources: ${response.status}`)
}
const { data, errors } = (await response.json()) as GraphQLResponse<{
@@ -197,7 +203,7 @@ async function FetchGamesFromDB(
export async function GetTotalGameCount(
options: Pick = {}
): Promise {
- const response = await fetch(BACKEND_URL, {
+ const response = await FetchBackend({
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
@@ -214,8 +220,7 @@ export async function GetTotalGameCount(
})
if (!response.ok) {
- const body = await response.text()
- throw new Error(`Failed to fetch game count: ${response.status} ${body}`)
+ throw new Error(`Failed to fetch game count: ${response.status}`)
}
const { data, errors } = (await response.json()) as GraphQLResponse<{
diff --git a/Frontend/src/tests/GameLogicFrontend.test.ts b/Frontend/src/tests/GameLogicFrontend.test.ts
index b707e4d..7d89ed0 100644
--- a/Frontend/src/tests/GameLogicFrontend.test.ts
+++ b/Frontend/src/tests/GameLogicFrontend.test.ts
@@ -278,6 +278,12 @@ describe('fetchGamesFromDB', () => {
await expect(FetchGamesFromDB(1, 0)).rejects.toThrow('games field not found')
})
+ it('turns network failures into a readable message', async () => {
+ global.fetch = vi.fn().mockRejectedValue(new TypeError('Failed to fetch'))
+
+ await expect(FetchGamesFromDB(1, 0)).rejects.toThrow('Could not reach the server')
+ })
+
it('throws when no data is returned and there are no errors either', async () => {
global.fetch = vi.fn().mockResolvedValue(MockResponse({}))
From 9a27e1697f95db1c82ac5a189dc1fd15d095fe46 Mon Sep 17 00:00:00 2001
From: catjoha04-byte
Date: Tue, 10 Nov 2026 20:02:39 +0100
Subject: [PATCH 7/8] chore: remove unused imports
---
Frontend/src/FrontendLogic/SearchPageLogicFrontend.ts | 2 +-
Frontend/src/pages/MainPage.tsx | 2 +-
2 files changed, 2 insertions(+), 2 deletions(-)
diff --git a/Frontend/src/FrontendLogic/SearchPageLogicFrontend.ts b/Frontend/src/FrontendLogic/SearchPageLogicFrontend.ts
index 91c3d11..4159648 100644
--- a/Frontend/src/FrontendLogic/SearchPageLogicFrontend.ts
+++ b/Frontend/src/FrontendLogic/SearchPageLogicFrontend.ts
@@ -1,5 +1,5 @@
import { Gql } from './LogicConnection'
-import { IsBoolean, IsInteger, IsString, IsStringArray, ReadStored, RemoveStored, WriteStored } from './Storage'
+import { IsBoolean, IsInteger, IsString, IsStringArray, ReadStored, WriteStored } from './Storage'
const filterStorageKey = 'GameStart:filtersSearchpage'
const sortStorageKey = 'GameStart:sortOptionSearchpage'
diff --git a/Frontend/src/pages/MainPage.tsx b/Frontend/src/pages/MainPage.tsx
index 11453a8..92a80e6 100644
--- a/Frontend/src/pages/MainPage.tsx
+++ b/Frontend/src/pages/MainPage.tsx
@@ -9,7 +9,7 @@ import {
import { FetchGenres } from '../FrontendLogic/SearchPageLogicFrontend'
import { Link } from 'react-router-dom'
import { useEffect, useState } from 'react'
-import { Autocomplete, Button, TextField, useMediaQuery, Card } from '@mui/material'
+import { Button } from '@mui/material'
import maskot_gamestart from '../assets/maskot_gamestart.webp'
import RecentReviews from '../components/RecentReviews'
import { GetRecentReviews } from '../FrontendLogic/ReviewLogicFrontend'
From baa4bea57b1d111ce3761a93febac74d7d449023 Mon Sep 17 00:00:00 2001
From: catjoha04-byte
Date: Tue, 10 Nov 2026 20:13:50 +0100
Subject: [PATCH 8/8] fix: remove lengthy error message text
---
Frontend/src/FrontendLogic/LogicConnection.ts | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/Frontend/src/FrontendLogic/LogicConnection.ts b/Frontend/src/FrontendLogic/LogicConnection.ts
index 2ca0644..c7e6654 100644
--- a/Frontend/src/FrontendLogic/LogicConnection.ts
+++ b/Frontend/src/FrontendLogic/LogicConnection.ts
@@ -1,7 +1,7 @@
export const BACKEND_URL = import.meta.env.VITE_BACKEND_URL ?? 'http://it2810-10.idi.ntnu.no:3001/'
export const NETWORK_ERROR_MESSAGE =
- 'Could not reach the server. Check your connection and try again.'
+ 'Could not reach the server.'
export async function Gql(query: string, variables: Record): Promise {
const token = GetStoredToken()