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/FrontendLogic/LogicConnection.ts b/Frontend/src/FrontendLogic/LogicConnection.ts index 0b50100..c7e6654 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.' + 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/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/components/ActiveGameCard.tsx b/Frontend/src/components/ActiveGameCard.tsx index adac08a..ce9d8b2 100644 --- a/Frontend/src/components/ActiveGameCard.tsx +++ b/Frontend/src/components/ActiveGameCard.tsx @@ -154,8 +154,12 @@ export default function ActiveGameCard({ {isWishlisted ? 'Remove from wishlist' : 'Add to wishlist'} )} - {error &&

{error}

} + {error && ( +

+ {error} +

+ )} 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/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 && ( + + )} - + { + setFriendCode(event.target.value) + setAddError(null) + }} + inputProps={{ + 'aria-label': 'Friend ID', + 'aria-invalid': addError ? true : undefined, + 'aria-describedby': addError ? 'addFriendError' : undefined + }} + /> + + + {addError && ( + + )} +
} /> {user && ownCode && ( @@ -278,7 +296,6 @@ export default function FriendPage() {

)} - {addError &&

{addError}

} {showOnlyStatus ? ( -
{statusPanel}
+
+ {statusPanel} +
) : (
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 71c4469..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' @@ -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) }) @@ -106,12 +110,11 @@ export default function MainPage() { />
- {error && ( -

- {error} -

- )} - +
@@ -119,6 +122,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." @@ -128,6 +132,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." @@ -136,7 +141,11 @@ export default function MainPage() { />
- +