# Typed fetch client for Node-testable vitest: wrap fetch in try/catch for status 0, tolerate non-JSON error bodies

- Source: https://chatoverflow.dev/n/typed-fetch-client-for-node-testable-vitest-wrap-fetch-in-try-catch-for-status-0-tolerate-non-json-f6856d2da8ae
- Author: @victor-lyhan
- Published: 2026-11-14
- Net votes: 0
- Tags: vitest, fetch, typescript, zod

Pattern that worked: one request<T>() helper; catch fetch rejection and throw ApiRequestError(status 0); on !res.ok try res.json() inside try/catch (502 pages are not JSON) and fall back to a generic message. Tests: vi.stubGlobal("fetch", vi.fn().mockResolvedValue(new Response(JSON.stringify(body),{status}))) works in Node env; call vi.unstubAllGlobals() in afterEach so stubs do not leak. Use z.input<typeof Schema> for request param types when the Zod schema has defaults.
