From 94b5eb72784a04043da3197aaa5e64bef8f3b80a Mon Sep 17 00:00:00 2001 From: tajniak81 <13187254+tajniak81@users.noreply.github.com> Date: Tue, 17 Nov 2026 13:49:47 +0100 Subject: [PATCH] Name the unreachable server in network errors The API client now throws NetworkError (with the URL) when a request gets no response, instead of letting fetch's TypeError through. Forms show "Can't reach the server at " and mention firewalls, VPNs and browser extensions, and other unexpected errors get their own message rather than being blamed on the connection. The OAuth callback uses the shared handling. Co-Authored-By: Claude Opus 5.5 --- Packages/api-client/src/index.test.ts | 22 ++++++++++++++- Packages/api-client/src/index.ts | 28 ++++++++++++++++++- .../frontend/src/composables/useFormErrors.ts | 20 +++++++++++-- Web-App/frontend/src/locales/de.json | 3 +- Web-App/frontend/src/locales/en.json | 3 +- Web-App/frontend/src/locales/es.json | 3 +- Web-App/frontend/src/locales/fr.json | 3 +- Web-App/frontend/src/locales/pl.json | 3 +- .../src/views/auth/OAuthCallbackView.vue | 8 ++++-- 9 files changed, 81 insertions(+), 12 deletions(-) diff --git a/Packages/api-client/src/index.test.ts b/Packages/api-client/src/index.test.ts index 1053f05..69596c4 100644 --- a/Packages/api-client/src/index.test.ts +++ b/Packages/api-client/src/index.test.ts @@ -1,7 +1,7 @@ // SPDX-License-Identifier: AGPL-3.0-or-later import { describe, expect, it, vi } from "vitest"; -import { ApiError, createClient, isManager, readEventStream } from "./index"; +import { ApiError, createClient, isManager, NetworkError, readEventStream } from "./index"; function jsonResponse(status: number, body: unknown) { return new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json" } }); @@ -24,6 +24,26 @@ describe("createClient", () => { await expect(client.readiness()).rejects.toBeInstanceOf(ApiError); }); + it("throws NetworkError naming the URL when the request gets no response", async () => { + const fetch = vi.fn(async () => { + throw new TypeError("Failed to fetch"); + }); + const err = await createClient({ baseUrl: "http://10.0.0.5:4086", fetch }) + .auth.login("a@b.c", "pw") + .catch((e) => e); + expect(err).toBeInstanceOf(NetworkError); + expect(err.url).toBe("http://10.0.0.5:4086/api/v1/auth/login"); + expect(String(err.reason)).toContain("Failed to fetch"); + }); + + it("lets aborts through unchanged", async () => { + const abort = new DOMException("stopped", "AbortError"); + const fetch = vi.fn(async () => { + throw abort; + }); + await expect(createClient({ baseUrl: "", fetch }).version()).rejects.toBe(abort); + }); + it("exposes error code, fields and mfaId", async () => { const fetch = vi.fn(async () => jsonResponse(400, { error: "validation", fields: { email: "taken" } })); const err = await createClient({ baseUrl: "", fetch }) diff --git a/Packages/api-client/src/index.ts b/Packages/api-client/src/index.ts index 3d5d2d1..ce07e24 100644 --- a/Packages/api-client/src/index.ts +++ b/Packages/api-client/src/index.ts @@ -217,6 +217,22 @@ export class ApiError extends Error { } } +/** + * The request never got an HTTP response: the server is down or unreachable, + * or something on the way (CORS, a firewall, a browser extension) blocked it. + */ +export class NetworkError extends Error { + constructor( + /** The URL that could not be reached. */ + public readonly url: string, + /** What fetch threw, e.g. "TypeError: Failed to fetch". */ + public readonly reason: unknown, + ) { + super(`Could not reach ${url}: ${reason instanceof Error ? reason.message : String(reason)}`); + this.name = "NetworkError"; + } +} + export interface ClientOptions { /** Base URL of docwell-server, or "" for same-origin. */ baseUrl: string; @@ -233,7 +249,17 @@ const enc = encodeURIComponent; export function createClient(opts: ClientOptions) { const base = opts.baseUrl.replace(/\/+$/, ""); - const doFetch = opts.fetch ?? globalThis.fetch.bind(globalThis); + const rawFetch = opts.fetch ?? globalThis.fetch.bind(globalThis); + + /** fetch, but a request that gets no response throws NetworkError (aborts stay as they are). */ + async function doFetch(url: string, init?: RequestInit): Promise { + try { + return await rawFetch(url, init); + } catch (e) { + if (e instanceof DOMException && e.name === "AbortError") throw e; + throw new NetworkError(url, e); + } + } async function request(method: string, path: string, body?: unknown): Promise { const headers: Record = { Accept: "application/json" }; diff --git a/Web-App/frontend/src/composables/useFormErrors.ts b/Web-App/frontend/src/composables/useFormErrors.ts index 0006f22..b6a721e 100644 --- a/Web-App/frontend/src/composables/useFormErrors.ts +++ b/Web-App/frontend/src/composables/useFormErrors.ts @@ -1,6 +1,6 @@ // SPDX-License-Identifier: AGPL-3.0-or-later -import { ApiError } from "@docwell/api-client"; +import { ApiError, NetworkError } from "@docwell/api-client"; import { ref } from "vue"; import { useI18n } from "vue-i18n"; @@ -28,8 +28,24 @@ export function useFormErrors() { message.value = err.serverMessage || (te(key) ? t(key) : t("errors.unknown")); return; } - message.value = t("errors.network"); + if (err instanceof NetworkError) { + message.value = t("errors.network", { server: serverName(err.url) }); + return; + } + // Not from the server at all: a bug in the app. Say so instead of + // blaming the connection, and keep the details for the console. + console.error(err); + message.value = t("errors.unexpected"); } return { message, fields, reset, show }; } + +/** "10.2.1.10:4086" from "http://10.2.1.10:4086/api/v1/auth/login"; the page's own host for relative URLs. */ +export function serverName(url: string): string { + try { + return new URL(url, window.location.href).host; + } catch { + return url; + } +} diff --git a/Web-App/frontend/src/locales/de.json b/Web-App/frontend/src/locales/de.json index 3f3ad1a..0ee5f31 100644 --- a/Web-App/frontend/src/locales/de.json +++ b/Web-App/frontend/src/locales/de.json @@ -107,7 +107,8 @@ "domain_not_allowed": "Für diese E-Mail-Domain ist keine Registrierung erlaubt.", "invalid_token": "Dieser Link ist ungültig oder abgelaufen.", "mfa_required": "Ein zweiter Anmeldeschritt ist nötig.", - "network": "Der Server ist nicht erreichbar. Prüfe deine Verbindung.", + "network": "Der Server {server} ist nicht erreichbar. Prüfe deine Verbindung und ob eine Firewall, ein VPN oder eine Browser-Erweiterung ihn blockiert.", + "unexpected": "In der App ist ein Fehler aufgetreten. Lade die Seite neu und versuche es noch einmal.", "unknown": "Der Server konnte die Anfrage nicht abschließen. Lade die Seite neu und versuche es noch einmal.", "conflict": "Das steht im Konflikt mit vorhandenen Daten.", "not_found": "Nicht gefunden.", diff --git a/Web-App/frontend/src/locales/en.json b/Web-App/frontend/src/locales/en.json index 4ce1234..0b8d98e 100644 --- a/Web-App/frontend/src/locales/en.json +++ b/Web-App/frontend/src/locales/en.json @@ -107,7 +107,8 @@ "domain_not_allowed": "Sign-up is not allowed for this email domain.", "invalid_token": "This link is invalid or has expired.", "mfa_required": "A second sign-in step is required.", - "network": "Can't reach the server. Check your connection.", + "network": "Can't reach the server at {server}. Check your connection, and that a firewall, VPN or browser extension isn't blocking it.", + "unexpected": "Something went wrong in the app. Reload the page and try again.", "unknown": "The server could not finish this request. Reload the page and try again.", "conflict": "That conflicts with existing data.", "not_found": "Not found.", diff --git a/Web-App/frontend/src/locales/es.json b/Web-App/frontend/src/locales/es.json index eec38c7..1a1acf6 100644 --- a/Web-App/frontend/src/locales/es.json +++ b/Web-App/frontend/src/locales/es.json @@ -107,7 +107,8 @@ "domain_not_allowed": "No se permite el registro con este dominio de correo.", "invalid_token": "Este enlace no es válido o ha caducado.", "mfa_required": "Hace falta un segundo paso para iniciar sesión.", - "network": "No se puede contactar con el servidor. Comprueba tu conexión.", + "network": "No se puede contactar con el servidor {server}. Comprueba tu conexión y que ningún cortafuegos, VPN o extensión del navegador lo esté bloqueando.", + "unexpected": "Algo ha fallado en la aplicación. Recarga la página e inténtalo de nuevo.", "unknown": "El servidor no pudo terminar esta solicitud. Recarga la página e inténtalo de nuevo.", "conflict": "Esto entra en conflicto con datos existentes.", "not_found": "No encontrado.", diff --git a/Web-App/frontend/src/locales/fr.json b/Web-App/frontend/src/locales/fr.json index 91ad05e..39547b1 100644 --- a/Web-App/frontend/src/locales/fr.json +++ b/Web-App/frontend/src/locales/fr.json @@ -107,7 +107,8 @@ "domain_not_allowed": "L’inscription n’est pas autorisée pour ce domaine d’e-mail.", "invalid_token": "Ce lien n’est pas valide ou a expiré.", "mfa_required": "Une deuxième étape de connexion est requise.", - "network": "Impossible de joindre le serveur. Vérifiez votre connexion.", + "network": "Impossible de joindre le serveur {server}. Vérifiez votre connexion et qu'aucun pare-feu, VPN ou extension du navigateur ne le bloque.", + "unexpected": "Une erreur s'est produite dans l'application. Rechargez la page et réessayez.", "unknown": "Le serveur n’a pas pu terminer cette requête. Rechargez la page et réessayez.", "conflict": "Cela entre en conflit avec des données existantes.", "not_found": "Introuvable.", diff --git a/Web-App/frontend/src/locales/pl.json b/Web-App/frontend/src/locales/pl.json index d9f774f..a58f7e1 100644 --- a/Web-App/frontend/src/locales/pl.json +++ b/Web-App/frontend/src/locales/pl.json @@ -107,7 +107,8 @@ "domain_not_allowed": "Rejestracja z tej domeny e-mail jest niedozwolona.", "invalid_token": "Ten link jest nieprawidłowy lub wygasł.", "mfa_required": "Wymagany jest drugi krok logowania.", - "network": "Brak połączenia z serwerem.", + "network": "Brak połączenia z serwerem {server}. Sprawdź połączenie oraz czy nie blokuje go zapora, VPN lub rozszerzenie przeglądarki.", + "unexpected": "Coś poszło nie tak w aplikacji. Odśwież stronę i spróbuj ponownie.", "unknown": "Serwer nie dokończył tego żądania. Odśwież stronę i spróbuj ponownie.", "conflict": "To koliduje z istniejącymi danymi.", "not_found": "Nie znaleziono.", diff --git a/Web-App/frontend/src/views/auth/OAuthCallbackView.vue b/Web-App/frontend/src/views/auth/OAuthCallbackView.vue index 23b0913..6cff73c 100644 --- a/Web-App/frontend/src/views/auth/OAuthCallbackView.vue +++ b/Web-App/frontend/src/views/auth/OAuthCallbackView.vue @@ -5,6 +5,7 @@ import { onMounted, ref } from "vue"; import { useRoute, useRouter } from "vue-router"; import { useI18n } from "vue-i18n"; import AuthCard from "../../components/AuthCard.vue"; +import { useFormErrors } from "../../composables/useFormErrors"; import { useAuthStore } from "../../stores/auth"; // Where Google, GitHub, Microsoft or an OpenID Connect provider sends people @@ -12,7 +13,8 @@ import { useAuthStore } from "../../stores/auth"; const auth = useAuthStore(); const route = useRoute(); const router = useRouter(); -const { t, te } = useI18n(); +const { t } = useI18n(); +const errors = useFormErrors(); const failure = ref(""); onMounted(async () => { @@ -33,8 +35,8 @@ onMounted(async () => { router.replace({ name: "login", query: redirect ? { redirect } : {}, state: { challenge: e.challenge } }); return; } - const key = e instanceof ApiError ? `errors.${e.code}` : "errors.network"; - failure.value = te(key) ? t(key) : t("errors.unknown"); + errors.show(e); + failure.value = errors.message.value || t("errors.unknown"); } });