mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-11-28 23:50:08 +00:00
feat(client): catch render errors instead of blanking the page (#1805)
* feat(client): catch render errors instead of blanking the page
There were no error boundaries anywhere, so one throw during render unmounted the
whole tree and left the user staring at a white page with no way back.
ErrorBoundary holds the state in a class — getDerivedStateFromError has no hook
equivalent — and renders a function component for the visible half, so the panel
can translate normally. TranslationContext isn't exported, so contextType was not
an option anyway.
Two things it does beyond showing a message. A chunk that 404s after a deploy gets
one reload rather than a retry button: React.lazy caches the rejected promise, so
retrying re-throws immediately. And the reload happens once per session, or a
genuinely missing chunk would spin the tab.
The global handlers in main.tsx cover what no boundary reaches — event handlers
and async code. They filter axios errors: the interceptor already redirects on
401/403 and there are 600+ toast.error call sites, so reporting again would mean
double toasts and, for the redirects, loops.
* feat(client): isolate routes, widgets and the shell chrome
The route boundary goes on the single line where all 16 protected routes render
their content, inside MobileShell rather than around it: the navigation survives,
so a broken page is something the user can walk away from instead of a dead end.
The mobile --m-* tokens live on the shell's .m-root too, so a fallback outside it
would render invisible.
key={location.pathname}, not resetKeys — ProtectedRoute is the same component at
the same position for every protected route, so otherwise a failure could follow
the user across a navigation.
The public routes render outside ProtectedRoute and were therefore uncovered,
including /login (where people land when everything else failed) and the two
anonymous share pages. PublicRoute wraps those seven.
The five global widgets and the shell chrome get fallback={null} each: a broken
widget should disappear quietly, and if BottomNav dies the user loses the very
thing they need to leave the route.
* feat(client): isolate the GL maps and the plugin frame
Both map wrappers put the boundary outside their Suspense, not inside: Suspense
handles a pending promise, a rejected one throws straight past it. Falling back to
the Leaflet renderer keeps a usable map rather than showing an error card — the
same downgrade the Suspense fallback already does while loading.
PluginFrame is third-party code rendering in our tree; a throw there should cost
the plugin, not the page. resetKeys={[pluginId]} so switching plugins clears it.
The locale loader had no .catch (TranslationContext.tsx). After a deploy the chunk
can be gone, which produced an unhandled rejection and left the UI silently on the
previous language. It now keeps the strings it has and says so in the console.
This commit is contained in:
@@ -0,0 +1,73 @@
|
||||
import { isChunkLoadError, reloadOnceForChunk, clearChunkReloadMarker } from './chunkReload';
|
||||
|
||||
beforeEach(() => {
|
||||
sessionStorage.clear();
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
describe('isChunkLoadError', () => {
|
||||
// One message per engine — the wording differs and none of them carry a code.
|
||||
it.each([
|
||||
['Vite', 'Failed to fetch dynamically imported module: /assets/Page-a1b2.js'],
|
||||
['Firefox', 'error loading dynamically imported module'],
|
||||
['Safari', 'Importing a module script failed.'],
|
||||
['Vite CSS', 'Unable to preload CSS for /assets/Page-a1b2.css'],
|
||||
])('FE-UTIL-CHUNK-001: recognises the %s wording', (_engine, message) => {
|
||||
expect(isChunkLoadError(new Error(message))).toBe(true);
|
||||
});
|
||||
|
||||
it('FE-UTIL-CHUNK-002: leaves ordinary errors alone', () => {
|
||||
expect(isChunkLoadError(new Error('Cannot read properties of undefined'))).toBe(false);
|
||||
expect(isChunkLoadError(null)).toBe(false);
|
||||
expect(isChunkLoadError(undefined)).toBe(false);
|
||||
});
|
||||
|
||||
it('FE-UTIL-CHUNK-003: also reads a plain string, since a rejection need not be an Error', () => {
|
||||
expect(isChunkLoadError('Failed to fetch dynamically imported module')).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe('reloadOnceForChunk', () => {
|
||||
function stubReload() {
|
||||
const reload = vi.fn();
|
||||
Object.defineProperty(window, 'location', { value: { ...window.location, reload }, writable: true });
|
||||
return reload;
|
||||
}
|
||||
|
||||
it('FE-UTIL-CHUNK-004: reloads the first time and refuses afterwards', () => {
|
||||
const reload = stubReload();
|
||||
expect(reloadOnceForChunk()).toBe(true);
|
||||
expect(reload).toHaveBeenCalledTimes(1);
|
||||
|
||||
// A chunk that is genuinely missing — bad deploy, stale proxy — would otherwise
|
||||
// put the tab in a reload loop.
|
||||
expect(reloadOnceForChunk()).toBe(false);
|
||||
expect(reload).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('FE-UTIL-CHUNK-005: clearing the marker lets the next deploy heal too', () => {
|
||||
const reload = stubReload();
|
||||
reloadOnceForChunk();
|
||||
clearChunkReloadMarker();
|
||||
expect(reloadOnceForChunk()).toBe(true);
|
||||
expect(reload).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
it('FE-UTIL-CHUNK-006: does not reload blind when storage is unavailable', () => {
|
||||
const reload = stubReload();
|
||||
vi.spyOn(Storage.prototype, 'getItem').mockImplementation(() => {
|
||||
throw new Error('storage blocked');
|
||||
});
|
||||
// Without the marker there is no loop protection, so showing the fallback with
|
||||
// its manual reload button is the safer answer.
|
||||
expect(reloadOnceForChunk()).toBe(false);
|
||||
expect(reload).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('FE-UTIL-CHUNK-007: clearing survives unavailable storage', () => {
|
||||
vi.spyOn(Storage.prototype, 'removeItem').mockImplementation(() => {
|
||||
throw new Error('storage blocked');
|
||||
});
|
||||
expect(() => clearChunkReloadMarker()).not.toThrow();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,56 @@
|
||||
/**
|
||||
* Recognising — and surviving — a lazy chunk that no longer exists.
|
||||
*
|
||||
* After a deploy the old index file still references hashed chunks that are gone
|
||||
* from the server, so a dynamic import fails for anyone with the tab still open.
|
||||
* React.lazy caches the rejected promise on the lazy object, which means retrying
|
||||
* the same render fails instantly and forever: the only cure is a reload that
|
||||
* fetches the new index.
|
||||
*
|
||||
* Kept out of the component module so main.tsx can use it without pulling React in.
|
||||
*/
|
||||
|
||||
const RELOAD_MARKER = 'trek:chunk-reload';
|
||||
|
||||
/** Vite's own message, plus what Chrome/Firefox/Safari say for a failed module fetch. */
|
||||
const CHUNK_ERROR_PATTERNS = [
|
||||
'failed to fetch dynamically imported module',
|
||||
'error loading dynamically imported module',
|
||||
'importing a module script failed',
|
||||
'unable to preload css',
|
||||
'dynamically imported module',
|
||||
];
|
||||
|
||||
export function isChunkLoadError(error: unknown): boolean {
|
||||
if (!error) return false;
|
||||
const message = error instanceof Error ? error.message : String(error);
|
||||
const haystack = message.toLowerCase();
|
||||
return CHUNK_ERROR_PATTERNS.some(p => haystack.includes(p));
|
||||
}
|
||||
|
||||
/**
|
||||
* Reload once per session for a given chunk failure, then give up and let the
|
||||
* fallback show. Without the marker a chunk that is genuinely missing — a broken
|
||||
* deploy, a proxy serving stale assets — would put the tab in a reload loop.
|
||||
*/
|
||||
export function reloadOnceForChunk(): boolean {
|
||||
try {
|
||||
if (sessionStorage.getItem(RELOAD_MARKER)) return false;
|
||||
sessionStorage.setItem(RELOAD_MARKER, String(Date.now()));
|
||||
} catch {
|
||||
// Private mode or a blocked storage partition: reloading blind would risk a
|
||||
// loop, so prefer showing the fallback with its manual reload button.
|
||||
return false;
|
||||
}
|
||||
window.location.reload();
|
||||
return true;
|
||||
}
|
||||
|
||||
/** Called once the app has rendered successfully, so the next deploy can heal too. */
|
||||
export function clearChunkReloadMarker(): void {
|
||||
try {
|
||||
sessionStorage.removeItem(RELOAD_MARKER);
|
||||
} catch {
|
||||
// Nothing to clear if storage is unavailable.
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
import { AxiosError } from 'axios';
|
||||
import { installGlobalErrorHandlers } from './globalErrorHandlers';
|
||||
|
||||
let teardown: () => void;
|
||||
let consoleError: ReturnType<typeof vi.spyOn>;
|
||||
let reload: ReturnType<typeof vi.fn>;
|
||||
|
||||
beforeEach(() => {
|
||||
sessionStorage.clear();
|
||||
consoleError = vi.spyOn(console, 'error').mockImplementation(() => {});
|
||||
reload = vi.fn();
|
||||
Object.defineProperty(window, 'location', { value: { ...window.location, reload }, writable: true });
|
||||
teardown = installGlobalErrorHandlers();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
teardown();
|
||||
consoleError.mockRestore();
|
||||
});
|
||||
|
||||
/** jsdom has no PromiseRejectionEvent, so build the shape the handler reads. */
|
||||
function rejectWith(reason: unknown) {
|
||||
const event = new Event('unhandledrejection') as Event & { reason: unknown };
|
||||
event.reason = reason;
|
||||
window.dispatchEvent(event);
|
||||
}
|
||||
|
||||
describe('global error handlers', () => {
|
||||
it('FE-UTIL-GLOBALERR-001: ignores axios rejections, which the app already reports itself', () => {
|
||||
// The interceptor rejects onward and there are 600+ toast.error call sites;
|
||||
// logging here as well would turn every handled 500 into a phantom crash.
|
||||
rejectWith(new AxiosError('Request failed with status code 500'));
|
||||
expect(consoleError).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('FE-UTIL-GLOBALERR-002: logs a genuine unhandled rejection', () => {
|
||||
const reason = new Error('nobody caught me');
|
||||
rejectWith(reason);
|
||||
expect(consoleError).toHaveBeenCalledWith('[unhandledrejection]', reason);
|
||||
});
|
||||
|
||||
it('FE-UTIL-GLOBALERR-003: reloads when a dynamic import rejects outside render', () => {
|
||||
// A lazy chunk can also be pulled in from an effect or a prefetch, where no
|
||||
// boundary is watching.
|
||||
rejectWith(new Error('Failed to fetch dynamically imported module: /assets/x-1.js'));
|
||||
expect(reload).toHaveBeenCalledTimes(1);
|
||||
expect(consoleError).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('FE-UTIL-GLOBALERR-004: logs an uncaught error from an event handler', () => {
|
||||
const error = new Error('thrown in onClick');
|
||||
window.dispatchEvent(new ErrorEvent('error', { error, message: error.message }));
|
||||
expect(consoleError).toHaveBeenCalledWith('[window.onerror]', error);
|
||||
});
|
||||
|
||||
it('FE-UTIL-GLOBALERR-005: heals a chunk error arriving as a window error event', () => {
|
||||
window.dispatchEvent(
|
||||
new ErrorEvent('error', { error: new Error('Unable to preload CSS for /assets/x.css') }),
|
||||
);
|
||||
expect(reload).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('FE-UTIL-GLOBALERR-006: teardown unsubscribes both listeners', () => {
|
||||
// Asserted through removeEventListener rather than by firing an event: an
|
||||
// ErrorEvent with nobody listening is an uncaught error, and vitest reports
|
||||
// that against the file even when every test passed.
|
||||
const remove = vi.spyOn(window, 'removeEventListener');
|
||||
teardown();
|
||||
expect(remove).toHaveBeenCalledWith('unhandledrejection', expect.any(Function));
|
||||
expect(remove).toHaveBeenCalledWith('error', expect.any(Function));
|
||||
|
||||
// The rejection path has no such side effect, so it is safe to prove silence.
|
||||
rejectWith(new Error('after teardown'));
|
||||
expect(consoleError).not.toHaveBeenCalled();
|
||||
|
||||
teardown = () => {};
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,58 @@
|
||||
import axios from 'axios'
|
||||
import { isChunkLoadError, reloadOnceForChunk } from './chunkReload'
|
||||
|
||||
/**
|
||||
* The half no boundary can reach: throws in event handlers, in async code, and
|
||||
* rejected promises nobody caught.
|
||||
*
|
||||
* Deliberately quiet. It logs, and it heals one specific case — a dynamic import
|
||||
* that failed because the chunk is gone after a deploy. It does not toast and it
|
||||
* does not redirect: the axios interceptor already redirects on 401/403 and
|
||||
* rewrites 429 (api/client.ts), and there are 600+ `toast.error` call sites that
|
||||
* report their own failures. Reacting again here would mean double toasts and, in
|
||||
* the redirect cases, redirect loops.
|
||||
*/
|
||||
|
||||
/** Axios rejects onward from its interceptor, so every caller without a catch lands here. */
|
||||
function isHandledNetworkError(reason: unknown): boolean {
|
||||
return axios.isAxiosError(reason)
|
||||
}
|
||||
|
||||
function onUnhandledRejection(event: PromiseRejectionEvent): void {
|
||||
const reason = event.reason
|
||||
|
||||
if (isChunkLoadError(reason)) {
|
||||
// A lazy import can reject outside render too — a prefetch, or a chunk pulled
|
||||
// in from an effect. Same cure, same once-per-session guard.
|
||||
reloadOnceForChunk()
|
||||
return
|
||||
}
|
||||
|
||||
if (isHandledNetworkError(reason)) return
|
||||
|
||||
console.error('[unhandledrejection]', reason)
|
||||
}
|
||||
|
||||
function onError(event: ErrorEvent): void {
|
||||
if (isChunkLoadError(event.error ?? event.message)) {
|
||||
reloadOnceForChunk()
|
||||
return
|
||||
}
|
||||
console.error('[window.onerror]', event.error ?? event.message)
|
||||
}
|
||||
|
||||
/**
|
||||
* Call once, before the app renders. Returns a teardown so tests can install and
|
||||
* remove it without leaking listeners between files.
|
||||
*/
|
||||
export function installGlobalErrorHandlers(): () => void {
|
||||
window.addEventListener('unhandledrejection', onUnhandledRejection)
|
||||
// Bubble phase only: the capture phase would also fire for every failed <img>
|
||||
// and <link>, which on a map-heavy app means hundreds of tile requests.
|
||||
window.addEventListener('error', onError)
|
||||
|
||||
return () => {
|
||||
window.removeEventListener('unhandledrejection', onUnhandledRejection)
|
||||
window.removeEventListener('error', onError)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user