24.9. An API client with interceptors and typed errors
Topics
This question is in
24. Build a small libraryMost apps wrap fetch in a small API client. Every request then shares one base URL, default headers and JSON handling, and two hooks run around it: request interceptors (add an auth token, a trace id) and response interceptors (unwrap an envelope, log timing). The client also gives failures a type: a server that answered 404 is an HttpError with its status and body, and a request that never got an answer is a NetworkError. That lets calling code write if (error instanceof HttpError && error.status === 404) instead of parsing messages.
Write the error classes and createClient(options) in client.js.
Signature
class ApiError extends Error // error.config
class HttpError extends ApiError // error.status, error.data, error.response
class NetworkError extends ApiError // error.cause
function createClient({ baseURL, headers }) // both optional; returns the client
client.request({ method, path, params, body, headers }) // returns a promise of the response
client.get(path, options) client.delete(path, options)
client.post(path, body, options) client.put(path, body, options)
client.useRequest(fn) // fn(config) returns the config (or a promise of it)
client.useResponse(fn) // fn(response) returns the response (or a promise of it)
// both return a function that removes the interceptor
// config: { method, url, headers, body }
// response: { status, headers, data, config }options in the helpers takes the same keys as request (params, headers), and the helper sets method, path and body.
Requirements
- The URL is
baseURLandpathjoined with exactly one/. Apaththat starts withhttp://orhttps://is used as it is, and withoutbaseURLthe path is used as it is. paramsis added as a query string built withURLSearchParams: an array adds one pair per item, andundefinedandnullvalues are left out. It is joined with?, or with&when the path already has a query, and it goes before any#fragment, which stays at the end ("/docs#intro"→/docs?a=1#intro).- The method is upper-cased;
requestwithout one usesGET. - Headers are the client's
headersmerged with the request's, with every name in lower case; the request's value wins. Each request gets its own new headers object. - Request interceptors run in the order they were added, each awaited, each receiving the config returned by the one before.
config.bodyis still the value passed in. A request interceptor that throws or rejects fails the request, andfetchis not called. - After the interceptors, the client calls the global
fetch(config.url, init)once, whereinitis{ method, headers }plusbodywhen there is one. A string body is sent as it is; any other body is sent asJSON.stringify(body), withcontent-type: application/jsonadded unless acontent-typeis already set. - The response's body is read as text. An empty body (a 204, for example) gives
datanull; acontent-typecontainingapplication/jsongives the parsed JSON; anything else gives the text. The result is{ status, headers, data, config }, whereheadersis theResponse'sHeadersobject. - A status outside 200–299 rejects with an
HttpError(messageRequest failed with status <status>) carryingstatus,data,responseandconfig. For such a response, a body that is not valid JSON is kept as text indata. - A successful response whose JSON is invalid rejects with an
ApiError(messageInvalid JSON response), not anHttpError. - When
fetchitself throws or rejects, the request rejects with aNetworkError(messageNetwork error: <the cause's message>), withcauseset to whatfetchthrew andconfigset. - Each error's
nameis its class name.HttpErrorandNetworkErrorare instances ofApiErrorand ofError. - Response interceptors run in order, awaited, only for successful responses (after
datais read); the request resolves to what the last one returns. - An interceptor that returns something that is not an object rejects the request with a
TypeError:A request interceptor must return the configorA response interceptor must return the response. - The function returned by
useRequestoruseResponseremoves exactly that interceptor; calling it again does nothing. Passing a non-function throws aTypeErrorwith the messageAn interceptor must be a function. Two clients never share interceptors.
Examples
const api = createClient({ baseURL: "https://api.example.com/v1", headers: { Accept: "application/json" } });
api.useRequest((config) => ({ ...config, headers: { ...config.headers, authorization: "Bearer abc" } }));
api.useResponse((response) => ({ ...response, data: response.data.result }));
const response = await api.get("/users", { params: { page: 2, tag: ["new", "vip"] } });
// fetch("https://api.example.com/v1/users?page=2&tag=new&tag=vip",
// { method: "GET", headers: { accept: "application/json", authorization: "Bearer abc" } })
// the server answers { "result": [...] }, so response.data is that arrayawait api.post("/users", { name: "Ada" });
// fetch(…/users, { method: "POST",
// headers: { accept: "application/json", authorization: "Bearer abc", "content-type": "application/json" },
// body: '{"name":"Ada"}' })try {
await api.get("/users/999");
} catch (error) {
error instanceof HttpError; // true when the server answered 404
error.status; // 404
error.data; // the parsed error body, e.g. { message: "Not found" }
error instanceof NetworkError; // true instead when there was no answer at all
}Environment
- Plain JavaScript in a browser page; the tests call the globals
createClient,ApiError,HttpErrorandNetworkErrorfromclient.js. - The page has no network. The tests replace
window.fetchwith a fake that records each call and answers with aResponse, so call the globalfetchwhen the request is made (do not keep a reference to it from when the file loaded). - Timeouts, retries, cancellation,
FormDataandBlobbodies are out of scope.
Hints
- Which steps happen in which order: building the config, the request interceptors, serializing the body,
fetch, reading the body, checking the status, the response interceptors? - A class that extends another must call
super(…)before touchingthis. What does each error class add on top of its parent? - How can a remove function find "its" interceptor if the same function was added twice?
The explanation comes with the course
A walkthrough of every line of a solution, the mistakes the tests catch, other ways to write it, and links to the lessons that teach each idea.
- Every line explained
- The mistakes each test catches
- Links to the lessons behind it