Error class for non-ok HTTP responses from the Fetch API. Captures the response body as text and JSON for debugging.
$ npm install @stores.com/http-error
const HttpError = require('@stores.com/http-error');
const response = await fetch('https://api.example.com/items');
if (!response.ok) {
throw await HttpError.from(response);
}Catching errors:
try {
const response = await fetch('https://api.example.com/items');
if (!response.ok) {
throw await HttpError.from(response);
}
} catch (err) {
console.error(err.message); // "404 Not Found"
console.error(err.text); // Raw response body
console.error(err.json); // Parsed JSON (if applicable)
console.error(err.cause); // Original Response object
}Creates an error with message "${status} ${statusText}" and sets cause to the response.
Async factory that creates an HttpError and captures the response body:
err.text— the response body as a stringerr.json— the parsed JSON (if the body is valid JSON)err.cause— the originalResponseobject
The original response is not consumed (uses response.clone()).