;
+}
+
+function greeting(who: string, answer: string | Error): MockLink.MockedResponse {
+ return {
+ request: { query: GREETING_QUERY, variables: { who } },
+ ...(answer instanceof Error ? { error: answer } : { result: { data: { greeting: answer } } }),
+ };
+}
+
+function setOnline(online: boolean) {
+ vi.spyOn(navigator, 'onLine', 'get').mockReturnValue(online);
+ act(() => {
+ window.dispatchEvent(new Event(online ? 'online' : 'offline'));
+ });
+}
+
+function renderBanner(mocks: MockLink.MockedResponse[] = [], children?: ReactNode) {
+ return render(
+ // MockedProvider renders a single child only.
+
+ <>
+
+ {children}
+ >
+ ,
+ );
+}
+
+afterEach(() => {
+ vi.useRealTimers();
+ vi.restoreAllMocks();
+});
+
+describe('ConnectionBanner', () => {
+ it('shows nothing while the connection is fine, but keeps the live region', () => {
+ renderBanner();
+ expect(screen.getByRole('status')).toBeEmptyDOMElement();
+ });
+
+ it('says when the connection is lost and when it comes back', () => {
+ vi.useFakeTimers();
+ renderBanner();
+
+ setOnline(false);
+ expect(screen.getByRole('status')).toHaveTextContent('Du er frakoblet.');
+
+ setOnline(true);
+ expect(screen.getByRole('status')).toHaveTextContent('Du er på nett igjen.');
+
+ act(() => {
+ vi.advanceTimersByTime(BACK_ONLINE_MS);
+ });
+ expect(screen.getByRole('status')).toBeEmptyDOMElement();
+ });
+
+ it('sends failed requests again when the connection comes back, and only those', async () => {
+ // Each mock answers once, so a second request for «ok» would fail and show «Feil for ok».
+ renderBanner(
+ [
+ greeting('failed', new TypeError('Failed to fetch')),
+ greeting('failed', 'Hei igjen'),
+ greeting('ok', 'Hei'),
+ ],
+ <>
+
+
+ >,
+ );
+ expect(await screen.findByText('Feil for failed')).toBeInTheDocument();
+ expect(await screen.findByText('Hei')).toBeInTheDocument();
+
+ setOnline(false);
+ setOnline(true);
+
+ expect(await screen.findByText('Hei igjen')).toBeInTheDocument();
+ await waitFor(() => expect(screen.getByText('Hei')).toBeInTheDocument());
+ expect(screen.queryByText('Feil for ok')).not.toBeInTheDocument();
+ });
+});
diff --git a/frontend/src/components/layout/ConnectionBanner.tsx b/frontend/src/components/layout/ConnectionBanner.tsx
new file mode 100644
index 0000000..e75a836
--- /dev/null
+++ b/frontend/src/components/layout/ConnectionBanner.tsx
@@ -0,0 +1,56 @@
+import { useEffect, useState } from 'react';
+import { useApolloClient } from '@apollo/client/react';
+import { useOnlineStatus } from '../../hooks/useOnlineStatus';
+import styles from './ConnectionBanner.module.css';
+
+/** How long «Du er på nett igjen» stays before the banner goes away. */
+export const BACK_ONLINE_MS = 4000;
+
+/**
+ * Tells the user when the connection is lost, and when it comes back. On the way back,
+ * every request that failed on the page is sent again, so the user does not have to find
+ * each «Prøv igjen» button. Requests that worked are left alone.
+ */
+export function ConnectionBanner() {
+ const online = useOnlineStatus();
+ const client = useApolloClient();
+ const [previous, setPrevious] = useState(online);
+ const [backOnline, setBackOnline] = useState(false);
+
+ // Updated during render instead of in an effect, so the text changes in the same paint.
+ if (online !== previous) {
+ setPrevious(online);
+ setBackOnline(online);
+ }
+
+ useEffect(() => {
+ if (!backOnline) return;
+
+ void client
+ .refetchQueries({
+ include: 'active',
+ onQueryUpdated: (query) => Boolean(query.getCurrentResult().error),
+ })
+ // A request that fails again shows its own error where it belongs.
+ .catch(() => undefined);
+
+ const timer = setTimeout(() => setBackOnline(false), BACK_ONLINE_MS);
+ return () => clearTimeout(timer);
+ }, [backOnline, client]);
+
+ const text = !online
+ ? 'Du er frakoblet. Vi henter det som mangler når nettet er tilbake.'
+ : backOnline
+ ? 'Du er på nett igjen.'
+ : '';
+
+ // The live region is always in the DOM, so screen readers announce every change (WCAG 4.1.3).
+ return (
+
+ {text &&
{text}
}
+
+ );
+}
diff --git a/frontend/src/components/layout/RouteErrorBoundary.tsx b/frontend/src/components/layout/RouteErrorBoundary.tsx
new file mode 100644
index 0000000..00637d8
--- /dev/null
+++ b/frontend/src/components/layout/RouteErrorBoundary.tsx
@@ -0,0 +1,53 @@
+import { Component, type ReactNode } from 'react';
+import { ErrorNotice } from '../ui/ErrorNotice';
+
+interface RouteErrorBoundaryProps {
+ /** The boundary starts over when this changes, so a link to another page works again. */
+ resetKey: string;
+ children: ReactNode;
+}
+
+interface RouteErrorBoundaryState {
+ error: unknown;
+ resetKey: string;
+}
+
+/**
+ * Catches a page that throws while it loads or renders. The pages are loaded on demand, so
+ * without this a lost connection between two pages would leave a blank screen. The header
+ * and footer stay, so the user can still get away.
+ */
+export class RouteErrorBoundary extends Component<
+ RouteErrorBoundaryProps,
+ RouteErrorBoundaryState
+> {
+ state: RouteErrorBoundaryState = { error: null, resetKey: this.props.resetKey };
+
+ static getDerivedStateFromError(error: unknown): Partial {
+ return { error };
+ }
+
+ static getDerivedStateFromProps(
+ props: RouteErrorBoundaryProps,
+ state: RouteErrorBoundaryState,
+ ): Partial | null {
+ return props.resetKey === state.resetKey ? null : { error: null, resetKey: props.resetKey };
+ }
+
+ render() {
+ if (this.state.error === null) return this.props.children;
+
+ // A failed import() is cached by the browser, so only a full reload fetches the page again.
+ // A reload also picks up new file names after a deploy.
+ return (
+
+
Siden kunne ikke vises
+ window.location.reload()}
+ />
+
+ );
+ }
+}
diff --git a/frontend/src/components/ui/EmptyState.module.css b/frontend/src/components/ui/EmptyState.module.css
new file mode 100644
index 0000000..a44b45b
--- /dev/null
+++ b/frontend/src/components/ui/EmptyState.module.css
@@ -0,0 +1,46 @@
+.empty {
+ display: grid;
+ justify-items: start;
+ gap: var(--space-3);
+ padding: var(--space-6) var(--space-5);
+ background: var(--color-surface-muted);
+ border-radius: var(--radius-md);
+ overflow-wrap: anywhere;
+}
+
+.icon {
+ width: 2.5rem;
+ height: 2.5rem;
+ fill: none;
+ stroke: var(--color-brand);
+ stroke-width: 1.5;
+ stroke-linecap: round;
+ stroke-linejoin: round;
+}
+
+@media (prefers-color-scheme: dark) {
+ .icon {
+ stroke: var(--color-accent);
+ }
+}
+
+.title {
+ font-family: var(--font-display);
+ font-size: var(--text-xl);
+ font-weight: 700;
+ line-height: 1.2;
+}
+
+.text {
+ display: grid;
+ gap: var(--space-2);
+ max-width: 60ch;
+ color: var(--color-text-muted);
+}
+
+.actions {
+ display: flex;
+ flex-wrap: wrap;
+ align-items: center;
+ gap: var(--space-3) var(--space-5);
+}
diff --git a/frontend/src/components/ui/EmptyState.tsx b/frontend/src/components/ui/EmptyState.tsx
new file mode 100644
index 0000000..c7f452f
--- /dev/null
+++ b/frontend/src/components/ui/EmptyState.tsx
@@ -0,0 +1,71 @@
+import type { ReactNode } from 'react';
+import styles from './EmptyState.module.css';
+
+type EmptyIcon = 'search' | 'bottle' | 'signpost';
+
+interface EmptyStateProps {
+ icon: EmptyIcon;
+ title: string;
+ /** h1 when the empty state is the whole page, so focus after navigation has a heading. */
+ titleAs?: 'h1' | 'h2' | 'p';
+ /** Why it is empty and what the user can try. */
+ children?: ReactNode;
+ /** Links that get the user further. */
+ actions?: ReactNode;
+}
+
+/** Decorative: the title says the same thing. */
+function Icon({ icon }: { icon: EmptyIcon }) {
+ const common = {
+ viewBox: '0 0 24 24',
+ 'aria-hidden': true,
+ focusable: false,
+ className: styles.icon,
+ } as const;
+
+ switch (icon) {
+ case 'search':
+ return (
+
+ );
+ case 'bottle':
+ return (
+
+ );
+ case 'signpost':
+ return (
+
+ );
+ }
+}
+
+/**
+ * A state with nothing to show, such as no search results or a page that does not exist.
+ * Unlike an error, nothing went wrong, so it is not announced as an alert. It says why
+ * the page is empty and gives the user somewhere to go.
+ */
+export function EmptyState({
+ icon,
+ title,
+ titleAs: Title = 'p',
+ children,
+ actions,
+}: EmptyStateProps) {
+ return (
+
+
+ {/* A page heading keeps the global h1 style, so every page title looks the same. */}
+ {title}
+ {children &&
{children}
}
+ {actions &&
{actions}
}
+
+ );
+}
diff --git a/frontend/src/components/ui/ErrorNotice.module.css b/frontend/src/components/ui/ErrorNotice.module.css
index 2fa8492..7e4ca9f 100644
--- a/frontend/src/components/ui/ErrorNotice.module.css
+++ b/frontend/src/components/ui/ErrorNotice.module.css
@@ -1,12 +1,40 @@
.notice {
display: grid;
- justify-items: start;
- gap: var(--space-3);
+ grid-template-columns: auto 1fr;
+ align-items: start;
+ column-gap: var(--space-4);
+ row-gap: var(--space-3);
padding-block: var(--space-5);
+ padding-inline-start: var(--space-4);
border-left: 4px solid var(--color-danger);
}
+.icon {
+ width: 1.75rem;
+ height: 1.75rem;
+ fill: none;
+ stroke: var(--color-danger);
+ stroke-width: 1.75;
+ stroke-linecap: round;
+ stroke-linejoin: round;
+}
+
+.text {
+ display: grid;
+ gap: var(--space-1);
+}
+
+.title {
+ font-weight: 700;
+}
+
+.detail {
+ color: var(--color-text-muted);
+}
+
.retry {
+ grid-column: 2;
+ justify-self: start;
min-height: var(--tap-target);
padding: 0 var(--space-5);
border: 0;
diff --git a/frontend/src/components/ui/ErrorNotice.test.tsx b/frontend/src/components/ui/ErrorNotice.test.tsx
new file mode 100644
index 0000000..2725714
--- /dev/null
+++ b/frontend/src/components/ui/ErrorNotice.test.tsx
@@ -0,0 +1,99 @@
+import { afterEach, describe, expect, it, vi } from 'vitest';
+import { act, render, screen } from '@testing-library/react';
+import userEvent from '@testing-library/user-event';
+import { axe } from 'vitest-axe';
+import { CombinedGraphQLErrors, ServerError } from '@apollo/client/errors';
+import { ErrorNotice } from './ErrorNotice';
+
+function setOnline(online: boolean) {
+ vi.spyOn(navigator, 'onLine', 'get').mockReturnValue(online);
+ act(() => {
+ window.dispatchEvent(new Event(online ? 'online' : 'offline'));
+ });
+}
+
+const serverDown = new ServerError('Service Unavailable', {
+ response: new Response('', { status: 503 }),
+ bodyText: 'Service Unavailable',
+});
+
+afterEach(() => {
+ vi.restoreAllMocks();
+});
+
+describe('ErrorNotice', () => {
+ it('shows only the message when it gets no error', () => {
+ render();
+ const alert = screen.getByRole('alert');
+ expect(alert).toHaveTextContent('Vi fikk ikke søkt akkurat nå.');
+ expect(alert.querySelectorAll('p')).toHaveLength(1);
+ expect(screen.queryByRole('button')).not.toBeInTheDocument();
+ });
+
+ it('explains a network failure and offers a retry', async () => {
+ const onRetry = vi.fn();
+ const user = userEvent.setup();
+ render(
+ ,
+ );
+
+ expect(screen.getByRole('alert')).toHaveAttribute('data-kind', 'network');
+ expect(screen.getByRole('alert')).toHaveTextContent('Vi fikk ikke kontakt med serveren');
+ await user.click(screen.getByRole('button', { name: 'Prøv igjen' }));
+ expect(onRetry).toHaveBeenCalledOnce();
+ });
+
+ it('says the problem is on our side when the server fails', () => {
+ render();
+ expect(screen.getByRole('alert')).toHaveAttribute('data-kind', 'server');
+ expect(screen.getByRole('alert')).toHaveTextContent('Feilen er hos oss, ikke hos deg.');
+ });
+
+ it('asks the user to wait after too many requests', () => {
+ const error = new CombinedGraphQLErrors({
+ errors: [{ message: 'Slow down', extensions: { code: 'TOO_MANY_ATTEMPTS' } }],
+ });
+ render();
+ expect(screen.getByRole('alert')).toHaveTextContent('Vent litt og prøv igjen.');
+ });
+
+ it('leaves out the retry button when trying again cannot help', () => {
+ const error = new CombinedGraphQLErrors({
+ errors: [{ message: 'Invalid cursor.', extensions: { code: 'BAD_USER_INPUT' } }],
+ });
+ render(
+ ,
+ );
+ expect(screen.getByRole('alert')).toHaveTextContent('Last inn siden på nytt');
+ expect(screen.queryByRole('button', { name: 'Prøv igjen' })).not.toBeInTheDocument();
+ });
+
+ it('switches to the offline text when the connection goes, and back when it returns', () => {
+ render();
+ expect(screen.getByRole('alert')).toHaveAttribute('data-kind', 'server');
+
+ setOnline(false);
+ expect(screen.getByRole('alert')).toHaveAttribute('data-kind', 'offline');
+ expect(screen.getByRole('alert')).toHaveTextContent('Du er ikke koblet til internett.');
+
+ setOnline(true);
+ expect(screen.getByRole('alert')).toHaveAttribute('data-kind', 'server');
+ });
+
+ it('says offline even without an error object', () => {
+ setOnline(false);
+ render();
+ expect(screen.getByRole('alert')).toHaveTextContent('Du er ikke koblet til internett.');
+ });
+
+ it('has no axe violations', async () => {
+ const { container } = render(
+ ,
+ );
+ expect(await axe(container)).toHaveNoViolations();
+ });
+});
diff --git a/frontend/src/components/ui/ErrorNotice.tsx b/frontend/src/components/ui/ErrorNotice.tsx
index 26ecc12..0e102fd 100644
--- a/frontend/src/components/ui/ErrorNotice.tsx
+++ b/frontend/src/components/ui/ErrorNotice.tsx
@@ -1,17 +1,94 @@
+import { useOnlineStatus } from '../../hooks/useOnlineStatus';
+import { classifyError, ERROR_DETAILS, isRetryable, type ErrorKind } from '../../lib/errors';
import styles from './ErrorNotice.module.css';
interface ErrorNoticeProps {
+ /** What failed, such as «Vi fikk ikke søkt akkurat nå.» */
message: string;
+ /** The error itself. With it, the notice also says why it failed and what to do. */
+ error?: unknown;
onRetry?: () => void;
className?: string;
}
-/** Error message that is announced at once, with a way to try again. */
-export function ErrorNotice({ message, onRetry, className = '' }: ErrorNoticeProps) {
+/** Decorative icon for each kind of error. The text says the same thing. */
+function ErrorIcon({ kind }: { kind: ErrorKind }) {
+ const common = {
+ viewBox: '0 0 24 24',
+ 'aria-hidden': true,
+ focusable: false,
+ className: styles.icon,
+ } as const;
+
+ switch (kind) {
+ case 'offline':
+ case 'network':
+ // A cloud with a line through it.
+ return (
+
+ );
+ case 'server':
+ // A server rack with a warning dot.
+ return (
+
+ );
+ case 'rateLimited':
+ return (
+
+ );
+ case 'unauthenticated':
+ return (
+
+ );
+ case 'notFound':
+ return (
+
+ );
+ default:
+ return (
+
+ );
+ }
+}
+
+/**
+ * Error message that is announced at once (role="alert"). With `error`, it shows
+ * the kind of problem (offline, server down, too many requests, …) with its own icon
+ * and advice, and leaves out «Prøv igjen» where trying again cannot help.
+ */
+export function ErrorNotice({ message, error, onRetry, className = '' }: ErrorNoticeProps) {
+ const online = useOnlineStatus();
+ const kind = classifyError(error, online);
+ const detail = error === undefined && online ? undefined : ERROR_DETAILS[kind];
+ const canRetry = onRetry !== undefined && isRetryable(kind);
+
return (
-
-
{message}
- {onRetry && (
+
+
+
+
{message}
+ {detail &&
{detail}
}
+
+ {canRetry && (
diff --git a/frontend/src/components/ui/index.ts b/frontend/src/components/ui/index.ts
index f594583..f630fc0 100644
--- a/frontend/src/components/ui/index.ts
+++ b/frontend/src/components/ui/index.ts
@@ -1,6 +1,7 @@
export { Bottle } from './Bottle';
export { ChipLink } from './Chip';
export { StarIcon, Stars } from './Stars';
+export { EmptyState } from './EmptyState';
export { ErrorNotice } from './ErrorNotice';
export { HeartIcon } from './HeartIcon';
export { SearchForm } from './SearchForm';
diff --git a/frontend/src/features/auth/AccountPage.test.tsx b/frontend/src/features/auth/AccountPage.test.tsx
index 1c9d22f..296c483 100644
--- a/frontend/src/features/auth/AccountPage.test.tsx
+++ b/frontend/src/features/auth/AccountPage.test.tsx
@@ -128,7 +128,7 @@ describe('AccountPage', () => {
it('stays logged in and says so when logging out fails', async () => {
const { user } = renderPage([
me(USER),
- { request: { query: LOGOUT_MUTATION }, error: new Error('Nede') },
+ { request: { query: LOGOUT_MUTATION }, error: new TypeError('Failed to fetch') },
]);
expect(await screen.findByText('student')).toBeInTheDocument();
@@ -143,7 +143,7 @@ describe('AccountPage', () => {
});
it('tells the user when the server cannot be reached', async () => {
- const { user } = renderPage([me(null), login(new Error('Nede'))]);
+ const { user } = renderPage([me(null), login(new TypeError('Failed to fetch'))]);
await signIn(user, 'Logg inn');
diff --git a/frontend/src/features/auth/api/authMessages.test.ts b/frontend/src/features/auth/api/authMessages.test.ts
new file mode 100644
index 0000000..8899b0d
--- /dev/null
+++ b/frontend/src/features/auth/api/authMessages.test.ts
@@ -0,0 +1,39 @@
+import { describe, expect, it } from 'vitest';
+import { CombinedGraphQLErrors, ServerError } from '@apollo/client/errors';
+import { authErrorMessage } from './authMessages';
+
+function graphQLError(extensions: Record) {
+ return new CombinedGraphQLErrors({ errors: [{ message: 'Fra serveren', extensions }] });
+}
+
+describe('authErrorMessage', () => {
+ it('uses the reason before the code', () => {
+ expect(
+ authErrorMessage(graphQLError({ code: 'BAD_USER_INPUT', reason: 'USERNAME_TOO_SHORT' })),
+ ).toBe('Brukernavnet må ha minst 3 tegn.');
+ });
+
+ it('has its own text for each auth code', () => {
+ expect(authErrorMessage(graphQLError({ code: 'INVALID_CREDENTIALS' }))).toBe(
+ 'Feil brukernavn eller passord.',
+ );
+ expect(authErrorMessage(graphQLError({ code: 'TOO_MANY_ATTEMPTS' }))).toContain('Vent litt');
+ });
+
+ it('says the server is at fault for an unknown GraphQL error', () => {
+ expect(authErrorMessage(graphQLError({ code: 'INTERNAL_SERVER_ERROR' }))).toContain(
+ 'Feilen er hos oss',
+ );
+ });
+
+ it('tells a lost connection from a server that is down', () => {
+ expect(authErrorMessage(new TypeError('Failed to fetch'))).toContain(
+ 'Vi fikk ikke kontakt med serveren',
+ );
+ const down = new ServerError('Bad Gateway', {
+ response: new Response('', { status: 502 }),
+ bodyText: '',
+ });
+ expect(authErrorMessage(down)).toContain('Feilen er hos oss');
+ });
+});
diff --git a/frontend/src/features/auth/api/authMessages.ts b/frontend/src/features/auth/api/authMessages.ts
index 8d0e24d..86f1174 100644
--- a/frontend/src/features/auth/api/authMessages.ts
+++ b/frontend/src/features/auth/api/authMessages.ts
@@ -1,4 +1,5 @@
import { CombinedGraphQLErrors } from '@apollo/client/errors';
+import { classifyError, ERROR_DETAILS } from '../../../lib/errors';
/** The rules the backend checks, so the form can say the same thing before asking. */
export const USERNAME_PATTERN = '^[a-z0-9_]{3,30}$';
@@ -35,8 +36,8 @@ export function authErrorMessage(error: unknown): string {
if (reason && REASONS[reason]) return REASONS[reason];
if (code && CODES[code]) return CODES[code];
}
- return 'Noe gikk galt. Prøv igjen.';
}
- return 'Vi fikk ikke kontakt med serveren. Sjekk nettet og prøv igjen.';
+ // Offline, server down, and the like: the same text as everywhere else in the app.
+ return ERROR_DETAILS[classifyError(error)];
}
diff --git a/frontend/src/features/landing/LandingView.tsx b/frontend/src/features/landing/LandingView.tsx
index cb87bfe..52e11a7 100644
--- a/frontend/src/features/landing/LandingView.tsx
+++ b/frontend/src/features/landing/LandingView.tsx
@@ -42,6 +42,7 @@ export function LandingView({ data, loading, error, refetch, now }: LandingViewP
) : (
diff --git a/frontend/src/features/my/MyView.tsx b/frontend/src/features/my/MyView.tsx
index dbe5ec9..ac1f5f4 100644
--- a/frontend/src/features/my/MyView.tsx
+++ b/frontend/src/features/my/MyView.tsx
@@ -32,7 +32,11 @@ export function MyView({ wines, savedCount, loading, error, refetch }: WishlistR
{loading && wines.length === 0 && }
{error && (
-
+
)}
{wines.length > 0 && }
diff --git a/frontend/src/features/search/SearchFilters.test.tsx b/frontend/src/features/search/SearchFilters.test.tsx
index 865ac74..f22ac27 100644
--- a/frontend/src/features/search/SearchFilters.test.tsx
+++ b/frontend/src/features/search/SearchFilters.test.tsx
@@ -151,6 +151,16 @@ describe('Filter på stor skjerm', () => {
expect(await screen.findByRole('list', { name: 'Søkeresultater' })).toBeInTheDocument();
});
+ it('kan hente filtrene på nytt etter en feil', async () => {
+ const failOnce = { ...filterOptionsMock({ fails: true }).mock, maxUsageCount: 1 };
+ const { user } = renderPage([searchMock(() => 3).mock, failOnce, filterOptionsMock().mock]);
+
+ await user.click(await screen.findByRole('button', { name: 'Hent filtrene igjen' }));
+
+ expect(await screen.findByRole('checkbox', { name: /Rødvin/ })).toBeInTheDocument();
+ expect(screen.queryByText('Vi fikk ikke hentet filtrene.')).not.toBeInTheDocument();
+ });
+
it('har ingen axe-brudd', async () => {
const { container } = renderPage([searchMock(() => 3).mock, filterOptionsMock().mock]);
await screen.findByRole('checkbox', { name: /Rødvin/ });
diff --git a/frontend/src/features/search/SearchPage.test.tsx b/frontend/src/features/search/SearchPage.test.tsx
index f169983..54f43d5 100644
--- a/frontend/src/features/search/SearchPage.test.tsx
+++ b/frontend/src/features/search/SearchPage.test.tsx
@@ -2,6 +2,7 @@ import { useEffect } from 'react';
import { describe, expect, it } from 'vitest';
import { act, render, screen, waitFor, within } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
+import { ServerError } from '@apollo/client/errors';
import type { MockLink } from '@apollo/client/testing';
import { MockedProvider } from '@apollo/client/testing/react';
import { MemoryRouter, Route, Routes, useNavigate } from 'react-router';
@@ -269,11 +270,16 @@ describe('SearchPage – tilstander', () => {
it('viser feilmelding og kan prøve igjen', async () => {
const failing: MockLink.MockedResponse = {
request: { query: SEARCH_WINES_QUERY, variables: () => true },
- error: new Error('Nede'),
+ error: new ServerError('Service Unavailable', {
+ response: new Response('', { status: 503 }),
+ bodyText: 'Service Unavailable',
+ }),
};
const { user } = renderPage([failing, searchMock(() => 1).mock]);
- expect(await screen.findByRole('alert')).toHaveTextContent('Vi fikk ikke søkt akkurat nå');
+ const alert = await screen.findByRole('alert');
+ expect(alert).toHaveTextContent('Vi fikk ikke søkt akkurat nå');
+ expect(alert).toHaveTextContent('Feilen er hos oss, ikke hos deg.');
await user.click(screen.getByRole('button', { name: 'Prøv igjen' }));
expect(await results()).toBeInTheDocument();
diff --git a/frontend/src/features/search/SearchPage.tsx b/frontend/src/features/search/SearchPage.tsx
index a19000a..51f3c45 100644
--- a/frontend/src/features/search/SearchPage.tsx
+++ b/frontend/src/features/search/SearchPage.tsx
@@ -30,6 +30,7 @@ export default function SearchPage() {
state={state}
filterGroups={filters.groups}
filtersError={filters.error}
+ onRetryFilters={filters.refetch}
onChangeSearch={changeSearch}
/>
);
diff --git a/frontend/src/features/search/SearchView.module.css b/frontend/src/features/search/SearchView.module.css
index 557a405..b42abb0 100644
--- a/frontend/src/features/search/SearchView.module.css
+++ b/frontend/src/features/search/SearchView.module.css
@@ -78,16 +78,6 @@
opacity: 0.6;
}
-.empty {
- display: grid;
- justify-items: start;
- gap: var(--space-2);
- padding: var(--space-5);
- background: var(--color-surface-muted);
- border-radius: var(--radius-md);
- overflow-wrap: anywhere;
-}
-
.more {
display: flex;
justify-content: center;
diff --git a/frontend/src/features/search/SearchView.tsx b/frontend/src/features/search/SearchView.tsx
index 4dafb01..16f1525 100644
--- a/frontend/src/features/search/SearchView.tsx
+++ b/frontend/src/features/search/SearchView.tsx
@@ -1,22 +1,17 @@
import { useEffect, useRef, useId } from 'react';
-import { Link } from 'react-router';
import { ErrorNotice } from '../../components/ui/ErrorNotice';
import { SearchForm } from '../../components/ui/SearchForm';
import { Skeleton } from '../../components/ui/Skeleton';
import { WineList } from '../../components/ui/WineList';
import { useMediaQuery } from '../../hooks/useMediaQuery';
import { formatCount, pluralize } from '../../lib/format';
-import {
- activeFilterCount,
- buildSearchUrl,
- type SearchState,
- type SortOption,
-} from '../../lib/searchParams';
+import { activeFilterCount, type SearchState, type SortOption } from '../../lib/searchParams';
import type { FilterGroup } from './api/toFilterGroups';
import type { WineSearchResult } from './api/useWineSearch';
import { ActiveFilters } from './components/ActiveFilters';
import { FilterDialog } from './components/FilterDialog';
import { FilterPanel } from './components/FilterPanel';
+import { NoResults } from './components/NoResults';
import styles from './SearchView.module.css';
type SearchViewProps = WineSearchResult & {
@@ -27,6 +22,7 @@ type SearchViewProps = WineSearchResult & {
state: SearchState;
filterGroups: FilterGroup[];
filtersError: Error | undefined;
+ onRetryFilters: () => void;
onChangeSearch: (changes: Partial) => void;
};
@@ -59,8 +55,8 @@ function describeStatus({
export function SearchView(props: SearchViewProps) {
const { wines, totalCount, loading, error, loadMoreError, hasNextPage, loadMore, refetch } =
props;
- const { query, text, onTextChange, onSubmit } = props;
- const { state, filterGroups, filtersError, onChangeSearch } = props;
+ const { text, onTextChange, onSubmit } = props;
+ const { state, filterGroups, filtersError, onRetryFilters, onChangeSearch } = props;
const sortId = useId();
const showSidebar = useMediaQuery('(min-width: 60rem)');
@@ -87,6 +83,7 @@ export function SearchView(props: SearchViewProps) {
state={state}
groups={filterGroups}
error={filtersError}
+ onRetry={onRetryFilters}
onChange={onChangeSearch}
/>
);
@@ -151,7 +148,9 @@ export function SearchView(props: SearchViewProps) {
- {error && }
+ {error && (
+
+ )}
{!error && loading && wines.length === 0 && }
@@ -161,19 +160,14 @@ export function SearchView(props: SearchViewProps) {
)}
- {noHits && (
-
-
- {query
- ? `Ingen viner passer til «${query}».`
- : 'Ingen viner passer til valgene dine.'}
-
- Se alle viner
-
- )}
+ {noHits && }
{loadMoreError && (
-
+
)}
{hasNextPage && !loadMoreError && (
diff --git a/frontend/src/features/search/api/useFilterOptions.ts b/frontend/src/features/search/api/useFilterOptions.ts
index bc1c382..ac4cf5f 100644
--- a/frontend/src/features/search/api/useFilterOptions.ts
+++ b/frontend/src/features/search/api/useFilterOptions.ts
@@ -7,14 +7,20 @@ import { toFilterGroups, type FilterGroup, type FilterOptionsData } from './toFi
export interface FilterOptionsResult {
groups: FilterGroup[];
error: Error | undefined;
+ refetch: () => void;
}
/** The old counts stay until the new ones arrive, so the panel does not jump between choices. */
export function useFilterOptions(state: SearchState): FilterOptionsResult {
- const { data, previousData, error } = useQuery(
+ const { data, previousData, error, refetch } = useQuery(
FILTER_OPTIONS_QUERY,
{ variables: toFilterVariables(state) },
);
- return { groups: toFilterGroups(data ?? previousData, state), error };
+ return {
+ groups: toFilterGroups(data ?? previousData, state),
+ error,
+ // A failed retry already shows up in `error`, so the rejected promise needs no handling.
+ refetch: () => void refetch().catch(() => undefined),
+ };
}
diff --git a/frontend/src/features/search/components/FilterPanel.module.css b/frontend/src/features/search/components/FilterPanel.module.css
index 7eceffa..f3d638b 100644
--- a/frontend/src/features/search/components/FilterPanel.module.css
+++ b/frontend/src/features/search/components/FilterPanel.module.css
@@ -4,10 +4,28 @@
}
.error {
+ display: grid;
+ justify-items: start;
+ gap: var(--space-2);
font-size: var(--text-sm);
color: var(--color-text-muted);
}
+.error strong {
+ color: var(--color-text);
+}
+
+.retry {
+ min-height: var(--tap-target);
+ padding: 0 var(--space-4);
+ border: 1px solid var(--color-border);
+ border-radius: var(--radius-pill);
+ background: var(--color-surface);
+ color: var(--color-text);
+ font-weight: 700;
+ cursor: pointer;
+}
+
.group {
min-width: 0;
margin: 0;
diff --git a/frontend/src/features/search/components/FilterPanel.tsx b/frontend/src/features/search/components/FilterPanel.tsx
index c9a1e0c..d222e50 100644
--- a/frontend/src/features/search/components/FilterPanel.tsx
+++ b/frontend/src/features/search/components/FilterPanel.tsx
@@ -1,4 +1,6 @@
import { useId, useState, type ChangeEvent } from 'react';
+import { useOnlineStatus } from '../../../hooks/useOnlineStatus';
+import { classifyError, ERROR_DETAILS, isRetryable } from '../../../lib/errors';
import { pluralize } from '../../../lib/format';
import {
RATING_OPTIONS,
@@ -17,14 +19,15 @@ interface FilterPanelProps {
state: SearchState;
groups: Group[];
error: Error | undefined;
+ onRetry?: () => void;
onChange: (changes: Partial) => void;
}
/** The filters themselves. The same panel is used in the sidebar and in the mobile dialog. */
-export function FilterPanel({ state, groups, error, onChange }: FilterPanelProps) {
+export function FilterPanel({ state, groups, error, onRetry, onChange }: FilterPanelProps) {
return (
);
}
+
+/**
+ * A quiet notice: the search results still work without the filters, and a failing
+ * search already has its own alert, so this one is not announced on its own.
+ */
+function FiltersError({ error, onRetry }: { error: Error; onRetry?: () => void }) {
+ const online = useOnlineStatus();
+ const kind = classifyError(error, online);
+
+ return (
+
+
+ Vi fikk ikke hentet filtrene. {ERROR_DETAILS[kind]}
+
+ {onRetry && isRetryable(kind) && (
+ // Its own name, since the search results can have a «Prøv igjen» button at the same time.
+
+ )}
+
+ );
+}
diff --git a/frontend/src/features/search/components/NoResults.module.css b/frontend/src/features/search/components/NoResults.module.css
new file mode 100644
index 0000000..f6e9e15
--- /dev/null
+++ b/frontend/src/features/search/components/NoResults.module.css
@@ -0,0 +1,8 @@
+.suggestions {
+ display: flex;
+ flex-wrap: wrap;
+ gap: var(--space-2);
+ margin: 0;
+ padding: 0;
+ list-style: none;
+}
diff --git a/frontend/src/features/search/components/NoResults.test.tsx b/frontend/src/features/search/components/NoResults.test.tsx
new file mode 100644
index 0000000..9959929
--- /dev/null
+++ b/frontend/src/features/search/components/NoResults.test.tsx
@@ -0,0 +1,53 @@
+import { describe, expect, it } from 'vitest';
+import { screen, within } from '@testing-library/react';
+import { axe } from 'vitest-axe';
+import { renderWithRouter } from '../../../test/render';
+import { SUGGESTIONS } from '../../landing/suggestions';
+import { NoResults } from './NoResults';
+
+describe('NoResults', () => {
+ it('helps with the search word when only a word was searched for', () => {
+ renderWithRouter();
+
+ expect(screen.getByText('Ingen viner passer til «finnesikke».')).toBeInTheDocument();
+ expect(screen.getByText(/navn, vingård, region og drue/)).toBeInTheDocument();
+ const suggestions = screen.getByRole('list', { name: 'Forslag' });
+ expect(within(suggestions).getAllByRole('link')).toHaveLength(SUGGESTIONS.length);
+ expect(screen.getByRole('link', { name: 'Se alle viner' })).toHaveAttribute('href', '/sok');
+ });
+
+ it('offers the same search without filters when the filters leave nothing', () => {
+ renderWithRouter(
+ ,
+ );
+
+ expect(
+ screen.getByText('Ingen viner passer til «pinot» med filtrene du har valgt.'),
+ ).toBeInTheDocument();
+ expect(screen.getByRole('link', { name: 'Søk etter «pinot» uten filtre' })).toHaveAttribute(
+ 'href',
+ '/sok?q=pinot&sort=name',
+ );
+ expect(screen.queryByRole('list', { name: 'Forslag' })).not.toBeInTheDocument();
+ });
+
+ it('offers to reset the filters, and keeps the sorting, when there is no search word', () => {
+ renderWithRouter();
+
+ expect(screen.getByText('Ingen viner passer til valgene dine.')).toBeInTheDocument();
+ expect(screen.getByRole('link', { name: 'Nullstill filtre' })).toHaveAttribute(
+ 'href',
+ '/sok?sort=alcohol',
+ );
+ });
+
+ it('is not announced as an error', () => {
+ renderWithRouter();
+ expect(screen.queryByRole('alert')).not.toBeInTheDocument();
+ });
+
+ it('has no axe violations', async () => {
+ const { container } = renderWithRouter();
+ expect(await axe(container)).toHaveNoViolations();
+ });
+});
diff --git a/frontend/src/features/search/components/NoResults.tsx b/frontend/src/features/search/components/NoResults.tsx
new file mode 100644
index 0000000..4f179ba
--- /dev/null
+++ b/frontend/src/features/search/components/NoResults.tsx
@@ -0,0 +1,62 @@
+import { Link } from 'react-router';
+import { ChipLink } from '../../../components/ui/Chip';
+import { EmptyState } from '../../../components/ui/EmptyState';
+import { activeFilterCount, buildSearchUrl, type SearchState } from '../../../lib/searchParams';
+import { SUGGESTIONS } from '../../landing/suggestions';
+import styles from './NoResults.module.css';
+
+/**
+ * What the search page shows when nothing matches. The advice depends on why: a search word
+ * that matches nothing, filters that leave nothing, or both together.
+ */
+export function NoResults({ state }: { state: SearchState }) {
+ const { q, sort } = state;
+ const hasFilters = activeFilterCount(state) > 0;
+ const allWines = Se alle viner;
+
+ if (q && hasFilters) {
+ return (
+
+ Søk etter «{q}» uten filtre
+ {allWines}
+ >
+ }
+ >
+
Filtrene snevrer inn søket. Fjern ett av dem, eller søk uten filtre.
+
+ );
+ }
+
+ if (q) {
+ return (
+
+
+ Søket ser etter ordet i navn, vingård, region og drue. Sjekk stavemåten, eller prøv et
+ kortere ord.
+
+
Eller start med et av disse:
+
+ {SUGGESTIONS.map(({ label, search }) => (
+
+ {label}
+
+ ))}
+
+
+ );
+ }
+
+ return (
+ Nullstill filtre}
+ >
+
Prøv å fjerne ett eller flere av filtrene.
+
+ );
+}
diff --git a/frontend/src/features/wine/WineView.tsx b/frontend/src/features/wine/WineView.tsx
index 69bb70c..7642ab9 100644
--- a/frontend/src/features/wine/WineView.tsx
+++ b/frontend/src/features/wine/WineView.tsx
@@ -2,6 +2,7 @@ import { Fragment, type ReactNode } from 'react';
import { Link, useLocation } from 'react-router';
import { Bottle } from '../../components/ui/Bottle';
import { ChipLink } from '../../components/ui/Chip';
+import { EmptyState } from '../../components/ui/EmptyState';
import { ErrorNotice } from '../../components/ui/ErrorNotice';
import { HeartIcon } from '../../components/ui/HeartIcon';
import { Skeleton } from '../../components/ui/Skeleton';
@@ -52,15 +53,22 @@ export function WineView({ wine, loading, error, refetch, notFound }: WineViewPr
{error && (
<>
Vin
-
+
>
)}
{notFound && (
- <>
-
Fant ikke vinen
-
Lenken kan være feil, eller så finnes ikke vinen lenger.
- >
+ // No links of its own: the back link above already leads to the search or the front page.
+
+
+ Lenken kan være feil, eller så finnes ikke vinen lenger. Prøv å søke etter navnet, eller
+ utforsk alle viner.
+
+
)}
{wine && !error && }
diff --git a/frontend/src/features/wine/api/useWineReviews.ts b/frontend/src/features/wine/api/useWineReviews.ts
index 69fa51e..e06fb5f 100644
--- a/frontend/src/features/wine/api/useWineReviews.ts
+++ b/frontend/src/features/wine/api/useWineReviews.ts
@@ -15,6 +15,9 @@ export interface ReviewDraft {
comment: string;
}
+/** How a save or delete went. A failure keeps the error, so the form can say why. */
+export type ReviewChange = { ok: true } | { ok: false; error: unknown };
+
export interface WineReviewsResult {
students: RatingSummary | null;
reviews: ApiReview[];
@@ -25,10 +28,8 @@ export interface WineReviewsResult {
loading: boolean;
error: Error | undefined;
refetch: () => void;
- /** Returns true when the review was saved. */
- save: (draft: ReviewDraft) => Promise;
- /** Returns true when the review was deleted. */
- remove: () => Promise;
+ save: (draft: ReviewDraft) => Promise;
+ remove: () => Promise;
saving: boolean;
}
@@ -60,23 +61,23 @@ export function useWineReviews(wineId: string): WineReviewsResult {
},
});
- async function save({ rating, comment }: ReviewDraft) {
+ async function save({ rating, comment }: ReviewDraft): Promise {
try {
await saveReview({
variables: { input: { wineId, userId, rating, comment: comment.trim() || null } },
});
- return true;
- } catch {
- return false; // The form shows its own message in Norwegian.
+ return { ok: true };
+ } catch (error) {
+ return { ok: false, error }; // The form shows its own message in Norwegian.
}
}
- async function remove() {
+ async function remove(): Promise {
try {
await deleteReview({ variables: { wineId, userId } });
- return true;
- } catch {
- return false;
+ return { ok: true };
+ } catch (error) {
+ return { ok: false, error };
}
}
diff --git a/frontend/src/features/wine/components/StudentReviews.test.tsx b/frontend/src/features/wine/components/StudentReviews.test.tsx
index a9cf463..b7e1e45 100644
--- a/frontend/src/features/wine/components/StudentReviews.test.tsx
+++ b/frontend/src/features/wine/components/StudentReviews.test.tsx
@@ -122,7 +122,7 @@ describe('StudentReviews', () => {
query: SAVE_REVIEW_MUTATION,
variables: { input: { wineId: WINE_ID, userId: USER_ID, rating: 5, comment: null } },
},
- error: new Error('Nede'),
+ error: new TypeError('Failed to fetch'),
},
]);
@@ -130,7 +130,9 @@ describe('StudentReviews', () => {
await user.click(screen.getByRole('button', { name: 'Lagre dommen' }));
await waitFor(() =>
- expect(screen.getByRole('status')).toHaveTextContent('Vi fikk ikke lagret dommen'),
+ expect(screen.getByRole('status')).toHaveTextContent(
+ 'Vi fikk ikke lagret dommen. Vi fikk ikke kontakt med serveren.',
+ ),
);
});
diff --git a/frontend/src/features/wine/components/StudentReviews.tsx b/frontend/src/features/wine/components/StudentReviews.tsx
index d953c45..a26053f 100644
--- a/frontend/src/features/wine/components/StudentReviews.tsx
+++ b/frontend/src/features/wine/components/StudentReviews.tsx
@@ -2,8 +2,9 @@ import { useState } from 'react';
import { Stars } from '../../../components/ui/Stars';
import { ErrorNotice } from '../../../components/ui/ErrorNotice';
import { Skeleton } from '../../../components/ui/Skeleton';
+import { classifyError, ERROR_DETAILS } from '../../../lib/errors';
import { formatRatingSummary, formatRelativeTime } from '../../../lib/format';
-import { useWineReviews, type ReviewDraft } from '../api/useWineReviews';
+import { useWineReviews, type ReviewChange, type ReviewDraft } from '../api/useWineReviews';
import { RatingDistribution } from './RatingDistribution';
import { ReviewForm } from './ReviewForm';
import styles from './StudentReviews.module.css';
@@ -14,6 +15,11 @@ interface StudentReviewsProps {
now?: Date;
}
+/** The text for the live region after a save or delete, with the reason when it failed. */
+function describeChange(change: ReviewChange, done: string, failed: string): string {
+ return change.ok ? done : `${failed} ${ERROR_DETAILS[classifyError(change.error)]}`;
+}
+
/** All ratings of one wine, the students' average, the user's own review and the newest reviews. */
export function StudentReviews({ wineId, now }: StudentReviewsProps) {
const {
@@ -33,14 +39,16 @@ export function StudentReviews({ wineId, now }: StudentReviewsProps) {
async function handleSave(draft: ReviewDraft) {
setMessage('');
- const saved = await save(draft);
- setMessage(saved ? 'Dommen er lagret.' : 'Vi fikk ikke lagret dommen. Prøv igjen.');
+ setMessage(
+ describeChange(await save(draft), 'Dommen er lagret.', 'Vi fikk ikke lagret dommen.'),
+ );
}
async function handleDelete() {
setMessage('');
- const deleted = await remove();
- setMessage(deleted ? 'Dommen er slettet.' : 'Vi fikk ikke slettet dommen. Prøv igjen.');
+ setMessage(
+ describeChange(await remove(), 'Dommen er slettet.', 'Vi fikk ikke slettet dommen.'),
+ );
}
return (
@@ -60,7 +68,11 @@ export function StudentReviews({ wineId, now }: StudentReviewsProps) {
{/* A failed fetch after the first one keeps the content; the live region reports the failure. */}
{error && !hasData && (
-
+
)}
{hasData && (
diff --git a/frontend/src/hooks/useOnlineStatus.ts b/frontend/src/hooks/useOnlineStatus.ts
new file mode 100644
index 0000000..6b4443e
--- /dev/null
+++ b/frontend/src/hooks/useOnlineStatus.ts
@@ -0,0 +1,16 @@
+import { useSyncExternalStore } from 'react';
+import { isOnline } from '../lib/errors';
+
+function subscribe(onChange: () => void) {
+ window.addEventListener('online', onChange);
+ window.addEventListener('offline', onChange);
+ return () => {
+ window.removeEventListener('online', onChange);
+ window.removeEventListener('offline', onChange);
+ };
+}
+
+/** True while the browser thinks it is online. Updates when the connection goes or comes back. */
+export function useOnlineStatus(): boolean {
+ return useSyncExternalStore(subscribe, isOnline, () => true);
+}
diff --git a/frontend/src/lib/errors.test.ts b/frontend/src/lib/errors.test.ts
new file mode 100644
index 0000000..23ec0c3
--- /dev/null
+++ b/frontend/src/lib/errors.test.ts
@@ -0,0 +1,89 @@
+import { describe, expect, it } from 'vitest';
+import { CombinedGraphQLErrors, ServerError, ServerParseError } from '@apollo/client/errors';
+import { classifyError, isRetryable } from './errors';
+
+function graphQLError(code?: string) {
+ return new CombinedGraphQLErrors({
+ errors: [{ message: 'Fra serveren', extensions: code ? { code } : undefined }],
+ });
+}
+
+function serverError(status: number) {
+ return new ServerError('Feil status', {
+ response: new Response('', { status }),
+ bodyText: '',
+ });
+}
+
+describe('classifyError', () => {
+ it('says offline when the browser has no connection, whatever the error is', () => {
+ expect(classifyError(serverError(503), false)).toBe('offline');
+ expect(classifyError(new TypeError('Failed to fetch'), false)).toBe('offline');
+ });
+
+ it('treats a request that never got an answer as a network problem', () => {
+ expect(classifyError(new TypeError('Failed to fetch'), true)).toBe('network');
+ expect(classifyError(new TypeError('Load failed'), true)).toBe('network');
+ expect(
+ classifyError(new TypeError('NetworkError when attempting to fetch resource.'), true),
+ ).toBe('network');
+ });
+
+ it('treats a page whose code could not be loaded as a network problem', () => {
+ const chrome = 'Failed to fetch dynamically imported module: /project2/assets/SearchPage.js';
+ expect(classifyError(new TypeError(chrome), true)).toBe('network');
+ expect(classifyError(new TypeError('Importing a module script failed.'), true)).toBe('network');
+ });
+
+ it('does not blame the network for a bug in our own code', () => {
+ const bug = new TypeError("Cannot read properties of undefined (reading 'name')");
+ expect(classifyError(bug, true)).toBe('unknown');
+ });
+
+ it('sorts HTTP status codes from the server', () => {
+ expect(classifyError(serverError(503), true)).toBe('server');
+ expect(classifyError(serverError(500), true)).toBe('server');
+ expect(classifyError(serverError(429), true)).toBe('rateLimited');
+ expect(classifyError(serverError(401), true)).toBe('unauthenticated');
+ expect(classifyError(serverError(404), true)).toBe('network');
+ expect(classifyError(serverError(418), true)).toBe('unknown');
+ });
+
+ it('treats a reply that is not JSON as a server problem', () => {
+ const parseError = new ServerParseError(new SyntaxError('Unexpected token <'), {
+ response: new Response('', { status: 200 }),
+ bodyText: '',
+ });
+ expect(classifyError(parseError, true)).toBe('server');
+ });
+
+ it('uses the code the backend sends with a GraphQL error', () => {
+ expect(classifyError(graphQLError('TOO_MANY_ATTEMPTS'), true)).toBe('rateLimited');
+ expect(classifyError(graphQLError('UNAUTHENTICATED'), true)).toBe('unauthenticated');
+ expect(classifyError(graphQLError('NOT_FOUND'), true)).toBe('notFound');
+ expect(classifyError(graphQLError('BAD_USER_INPUT'), true)).toBe('badInput');
+ expect(classifyError(graphQLError('INTERNAL_SERVER_ERROR'), true)).toBe('server');
+ });
+
+ it('treats a GraphQL error without a known code as a server problem', () => {
+ expect(classifyError(graphQLError(), true)).toBe('server');
+ expect(classifyError(graphQLError('SOMETHING_NEW'), true)).toBe('server');
+ });
+
+ it('falls back to unknown for anything else', () => {
+ expect(classifyError(new Error('Nede'), true)).toBe('unknown');
+ expect(classifyError('a string', true)).toBe('unknown');
+ expect(classifyError(undefined, true)).toBe('unknown');
+ });
+});
+
+describe('isRetryable', () => {
+ it('offers a retry only where trying again can help', () => {
+ expect(isRetryable('offline')).toBe(true);
+ expect(isRetryable('server')).toBe(true);
+ expect(isRetryable('rateLimited')).toBe(true);
+ expect(isRetryable('notFound')).toBe(false);
+ expect(isRetryable('badInput')).toBe(false);
+ expect(isRetryable('unauthenticated')).toBe(false);
+ });
+});
diff --git a/frontend/src/lib/errors.ts b/frontend/src/lib/errors.ts
new file mode 100644
index 0000000..bce8d5e
--- /dev/null
+++ b/frontend/src/lib/errors.ts
@@ -0,0 +1,90 @@
+import { CombinedGraphQLErrors, ServerError, ServerParseError } from '@apollo/client/errors';
+
+/**
+ * What kind of problem an error is, from the user's point of view. Each kind gets its own
+ * text and icon, so the user can tell "my network is down" from "the site has a problem".
+ */
+export type ErrorKind =
+ | 'offline'
+ | 'network'
+ | 'server'
+ | 'rateLimited'
+ | 'unauthenticated'
+ | 'notFound'
+ | 'badInput'
+ | 'unknown';
+
+/** Codes the backend puts in `extensions.code`, mapped to a kind. */
+const GRAPHQL_CODES: Record = {
+ TOO_MANY_ATTEMPTS: 'rateLimited',
+ UNAUTHENTICATED: 'unauthenticated',
+ NOT_FOUND: 'notFound',
+ BAD_USER_INPUT: 'badInput',
+ GRAPHQL_VALIDATION_FAILED: 'badInput',
+ INTERNAL_SERVER_ERROR: 'server',
+};
+
+/**
+ * How browsers word a request that failed: «Failed to fetch» (Chrome), «NetworkError when
+ * attempting to fetch resource» (Firefox), «Load failed» (Safari), and the variants for a
+ * module that could not be loaded.
+ */
+const NETWORK_MESSAGE = /fetch|network|load failed|dynamically imported module|importing a module/i;
+
+function fromStatusCode(status: number): ErrorKind {
+ if (status === 429) return 'rateLimited';
+ if (status === 401 || status === 403) return 'unauthenticated';
+ // Apache answers 404 when the API is not where the app expects it, so the API is out of reach.
+ if (status === 404) return 'network';
+ if (status >= 500) return 'server';
+ return 'unknown';
+}
+
+/**
+ * Sorts an error from Apollo (or anything else that was thrown) into an `ErrorKind`.
+ * `online` is passed in so the result follows the browser's connection state.
+ */
+export function classifyError(error: unknown, online = isOnline()): ErrorKind {
+ if (!online) return 'offline';
+
+ if (CombinedGraphQLErrors.is(error)) {
+ for (const graphQLError of error.errors) {
+ const code = graphQLError.extensions?.code;
+ if (typeof code === 'string' && GRAPHQL_CODES[code]) return GRAPHQL_CODES[code];
+ }
+ return 'server';
+ }
+
+ if (ServerError.is(error)) return fromStatusCode(error.statusCode);
+ // A reply that is not JSON, such as an error page from Apache in front of a stopped backend.
+ if (ServerParseError.is(error)) return 'server';
+ // fetch, and import() of a page's code, reject with a TypeError when the request never got
+ // an answer. A bug in our own code can also throw a TypeError, so the message decides.
+ if (error instanceof TypeError && NETWORK_MESSAGE.test(error.message)) return 'network';
+
+ return 'unknown';
+}
+
+/** Text that explains a kind of error and what the user can do about it. */
+export const ERROR_DETAILS: Record = {
+ offline: 'Du er ikke koblet til internett. Sjekk tilkoblingen og prøv igjen.',
+ network: 'Vi fikk ikke kontakt med serveren. Sjekk nettet og prøv igjen om litt.',
+ server: 'Feilen er hos oss, ikke hos deg. Prøv igjen om litt.',
+ rateLimited: 'Du har sendt mange forespørsler på kort tid. Vent litt og prøv igjen.',
+ unauthenticated: 'Du må være logget inn for å gjøre dette.',
+ notFound: 'Vi finner ikke det du leter etter. Lenken kan være feil eller utdatert.',
+ badInput: 'Noe i forespørselen var ugyldig. Last inn siden på nytt og prøv igjen.',
+ unknown: 'Noe uventet gikk galt. Prøv igjen.',
+};
+
+/** Kinds where trying the same request again right away cannot help. */
+const NOT_RETRYABLE: ReadonlySet = new Set(['unauthenticated', 'notFound', 'badInput']);
+
+export function isRetryable(kind: ErrorKind): boolean {
+ return !NOT_RETRYABLE.has(kind);
+}
+
+/** The browser's own view of the connection. Assumes online where `navigator` is missing. */
+export function isOnline(): boolean {
+ return typeof navigator === 'undefined' || navigator.onLine !== false;
+}