@harshilrajput/universal-api-errors-fetch
v0.1.3
Published
Fetch adapter for universal-api-errors: turns a failed Response or network error into a UniversalError.
Downloads
662
Maintainers
Readme
@harshilrajput/universal-api-errors-fetch
fetch adapter for universal-api-errors.
Turns a failed Response or a network-level fetch rejection into a UniversalError.
Install
npm install @harshilrajput/universal-api-errors-fetch
# or: pnpm add @harshilrajput/universal-api-errors-fetch
# or: yarn add @harshilrajput/universal-api-errors-fetch@harshilrajput/universal-api-errors-core comes along automatically as a regular dependency —
no separate install needed.
Usage
fetch never throws for HTTP error statuses (404, 500, ...) — only for genuine network
failures (offline, DNS, an aborted request). parseFetchError handles both cases, which is why,
unlike every other parser in this ecosystem, it's async: reading a Response body requires an
await.
import { parseFetchError } from '@harshilrajput/universal-api-errors-fetch';
// 1. HTTP error status
const response = await fetch('/api/user');
if (!response.ok) {
const error = await parseFetchError(response);
if (error.isUnauthorized) redirectToLogin();
}
// 2. Network failure / abort
try {
await fetch('/api/user');
} catch (err) {
const error = await parseFetchError(err);
if (error.isOffline) showOfflineBanner();
}Reading the response body uses response.clone(), so calling parseFetchError(response) never
consumes the stream — you can still read response.json() yourself afterwards if you need the
body for something else.
For the non-Response branch (network failures, AbortError), this delegates straight to
the core package's parseError(), which already classifies those from the error's
code/message — keeping that heuristic in one place instead of two copies drifting apart.
Everything from core, too
This package re-exports the entire
@harshilrajput/universal-api-errors-core
public API, so you don't need a separate import (or a separate npm install) to reach the generic
surface — parseError, createUniversalError, the UniversalError class, retry, normalizeValidation,
configureLogger, and every type, all from this one package:
import { parseFetchError, parseError, retry, UniversalError } from '@harshilrajput/universal-api-errors-fetch';License
MIT
