Name the unreachable server in network errors
CI / desktop (ubuntu-latest) (push) Successful in 1h32m41s
CI / mobile (push) Failing after 6m6s
CI / docker (push) Failing after 1h36m43s
Docs / build (push) Failing after 10m47s
Docs / deploy (push) Skipped
CI / desktop (macos-latest) (push) Canceled after 0s
CI / desktop (windows-latest) (push) Canceled after 0s
CI / go (Media) (push) Successful in 11m1s
CI / go (Server) (push) Failing after 20m3s
CI / go (Web-App) (push) Canceled after 0s
CI / frontend (push) Failing after 10m58s

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 <host>" 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 <noreply@anthropic.com>
This commit is contained in:
tajniak81andClaude Opus 5.5 committed 2026-11-17 13:49:47 +01:00
1 parent e4baa6d7c8
commit 94b5eb7278
9 files changed
+81 -12

No files matched your search

+21 -1
View File
@@ -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 })
+27 -1
View File
@@ -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<Response> {
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<T>(method: string, path: string, body?: unknown): Promise<T> {
const headers: Record<string, string> = { Accept: "application/json" };
@@ -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;
}
}
+2 -1
View File
@@ -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.",
+2 -1
View File
@@ -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.",
+2 -1
View File
@@ -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.",
+2 -1
View File
@@ -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.",
+2 -1
View File
@@ -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.",
@@ -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");
}
});
</script>