Skip to content
JavaScript

Fetch Wrapper

Wrap fetch with timeout, error handling, and JSON parsing.

By EZ4Code Team
fetchhttpwrapper

Code

async function request(url, options = {}, timeout = 10000) {
  const controller = new AbortController();
  const timer = setTimeout(() => controller.abort(), timeout);
  try {
    const res = await fetch(url, { ...options, signal: controller.signal });
    clearTimeout(timer);
    if (!res.ok) throw new Error(`HTTP ${res.status}`);
    const contentType = res.headers.get("content-type");
    return contentType?.includes("application/json")
      ? await res.json()
      : await res.text();
  } catch (err) {
    clearTimeout(timer);
    throw err;
  }
}

Explanation

Implements request timeout via AbortController, automatically parsing data based on response type.

More JavaScript Snippets