Sub topic 12
Putting It Together: A Reusable Fetch Helper
This chapter assumes you have worked through the earlier chapters. You should be comfortable with response.ok, reading bodies with json() and text(), sending JSON with JSON.stringify, and timeouts with AbortSignal.timeout(). You should also be fluent with async/await and try/catch.
Why a Wrapper Helps
Every correct fetch call repeats the same steps. You set default headers, encode a JSON body, add a timeout, check response.ok, and pick the right body reader. If you copy that code into every call site, some copies will drift. One copy will forget the ok check, and another will parse an empty 204 response as JSON and throw.
A wrapper is a small function that does those steps once. The function that calls it then has only two outcomes to handle: it gets parsed data, or it catches a typed error.
How the Helper Works
The Code
Save this as http.js and load it as an ES module. The example at the bottom uses top-level await, which works only in modules.
export class HttpError extends Error {
constructor(response, body) {
super(`HTTP ${response.status} ${response.statusText}`);
this.name = 'HttpError';
this.status = response.status;
this.body = body;
}
}
export async function request(url, { json, timeout = 10000, headers, ...options } = {}) {
const init = {
...options,
headers: { Accept: 'application/json', ...headers },
signal: options.signal ?? AbortSignal.timeout(timeout)
};
if (json !== undefined) {
init.body = JSON.stringify(json);
init.headers['Content-Type'] = 'application/json';
}
const response = await fetch(url, init);
const isJson = response.headers.get('content-type')?.includes('application/json');
const body = response.status === 204 ? null : isJson ? await response.json() : await response.text();
if (!response.ok) throw new HttpError(response, body);
return body;
}
try {
const user = await request('https://api.example.com/users', {
method: 'POST',
json: { name: 'Ada' }
});
console.log('Created:', user);
} catch (err) {
if (err instanceof HttpError) {
console.error(`Server said ${err.status}:`, err.body);
} else if (err.name === 'TimeoutError') {
console.error('Request timed out');
} else {
console.error('Network problem:', err.message);
}
}Design Choices
| Choice | Reason |
|---|---|
| `json` option separate from `body` | Callers pass plain objects. The helper encodes them and sets `Content-Type` so the two always match. |
| Body read before the `ok` check | Error responses often carry a useful message, such as validation details, and `HttpError.body` keeps it. |
| `HttpError` subclass | `instanceof HttpError` separates "the server answered with an error" from "no answer arrived." |
| `options.signal ?? AbortSignal.timeout(timeout)` | A caller's own `AbortController` takes priority. Otherwise every request gets a deadline. |
| 204 check | A No Content response has an empty body, and `json()` would throw on it. |
Common Mistakes
Other mistakes to watch for:
- Ignoring the content type when parsing. Proxies and gateways often return HTML error pages. Calling
json()on one throws a confusingSyntaxErrorthat hides the real status. - Passing a caller's signal and expecting the timeout too. When a caller supplies
signal, the default timeout is skipped. To get both, combine them withAbortSignal.any([signal, AbortSignal.timeout(ms)])in browsers that support it. - Adding too much. Retries, caching, and auth refresh are tempting extras. Add each one only when you need it, because every feature makes the error handling harder to reason about.
Exercise
Add get(url, options) and del(url, options) helpers built on request(). Then explain what del returns when the server replies with 204 No Content, and what happens when it replies with 404 and a JSON body { "error": "not found" }.
Show answer
const get = (url, options = {}) => request(url, { ...options, method: 'GET' }); and const del = (url, options = {}) => request(url, { ...options, method: 'DELETE' });. On 204, the status check sets the body to null and response.ok is true, so del resolves to null. On 404, the body is parsed as JSON, response.ok is false, and the promise rejects with an HttpError whose status is 404 and whose body is { error: 'not found' }.
Exercise
A caller passes headers: new Headers({ Authorization: 'Bearer abc' }) and the server responds 401. Why, and what one-line change inside request() fixes it?
Show answer
Spreading a Headers instance copies no entries, so the Authorization header is never sent. Normalize before merging: headers: { Accept: 'application/json', ...Object.fromEntries(new Headers(headers)) }. This works for plain objects, arrays of pairs, Headers instances, and undefined.