UNPKG

@lodestar/api

Version:

A Typescript REST client for the Ethereum Consensus API

68 lines 2.3 kB
/** * Native fetch with transparent and consistent error handling * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/fetch) */ async function wrappedFetch(url, init) { try { // This function wraps global `fetch` which should only be directly called here // biome-ignore lint/style/noRestrictedGlobals: <explanation> return await fetch(url, init); } catch (e) { throw new FetchError(url, e); } } export { wrappedFetch as fetch }; export function isFetchError(e) { return e instanceof FetchError; } export class FetchError extends Error { constructor(url, e) { if (isNativeFetchFailedError(e)) { super(`Request to ${url.toString()} failed, reason: ${e.cause.message}`); this.type = "failed"; this.code = e.cause.code || "ERR_FETCH_FAILED"; this.cause = e.cause; } else if (isNativeFetchInputError(e)) { // For input errors the e.message is more detailed super(e.message); this.type = "input"; this.code = e.cause.code || "ERR_INVALID_INPUT"; this.cause = e.cause; } else if (isNativeFetchAbortError(e)) { super(`Request to ${url.toString()} was aborted`); this.type = "aborted"; this.code = "ERR_ABORTED"; } else if (isNativeFetchTimeoutError(e)) { super(`Request to ${url.toString()} timed out`); this.type = "timeout"; this.code = "ERR_TIMEOUT"; } else { super(e.message); this.type = "unknown"; this.code = "ERR_UNKNOWN"; } this.name = this.constructor.name; } } function isNativeFetchError(e) { return e instanceof TypeError && e.cause instanceof Error; } function isNativeFetchFailedError(e) { return isNativeFetchError(e) && e.message === "fetch failed"; } function isNativeFetchInputError(e) { return isNativeFetchError(e) && e.cause.input !== undefined; } function isNativeFetchAbortError(e) { return e instanceof DOMException && e.name === "AbortError"; } function isNativeFetchTimeoutError(e) { return e instanceof DOMException && e.name === "TimeoutError"; } //# sourceMappingURL=fetch.js.map