Skip to content

fetchOrThrow

Wraps fetch so that a non-2xx response rejects with an HttpError, instead of resolving like any other response — the throwing counterpart to safeFetch, for when a failed request should fail loud. Network errors reject as fetch itself rejects them.

Available since v3.1.11

import { fetchOrThrow } from '@helpers4/fetch';
// or, from the all-in-one package (same code, one install):
import { fetchOrThrow } from 'helpers4/fetch';
fetchOrThrow(input: RequestInfo | URL, init?: RequestInit): Promise<Response>
ParameterTypeDescription
inputRequestInfo | URLURL or `Request` object passed to `fetch`
initRequestInitOptional `RequestInit` options passed to `fetch` (optional)

Promise<Response> — The response, body unread, when its status is 2xx

Resolves with the response on success, rejects with an HttpError otherwise.

const response = await fetchOrThrow('https://api.example.com/repo');
const repo = await response.json();

HttpError carries the status, the URL and the response, so a caller can branch on it.

try {
  await fetchOrThrow('https://api.example.com/missing');
} catch (error) {
  if (error instanceof HttpError && error.status === 404) {
    // error.message => 'HTTP 404 Not Found: https://api.example.com/missing'
  }
}

View source on GitHub