目錄
✅ Create a Custom Fetch Wrapper
? Add Interceptor-Like Behavior
? Centralized Error Handling
? Optional: Add Request Timeout
✅ Summary
首頁 web前端 js教程 將Fetch API與攔截器和錯誤處理

將Fetch API與攔截器和錯誤處理

Jul 26, 2025 am 08:15 AM
錯誤處理

雖然Fetch API沒有內置攔截器和全局錯誤處理,但可以通過封裝函數實現;2. 在自定義apiClient中,請求攔截可在發送前添加認證頭和默認配置,響應攔截可統一處理響應數據或錯誤;3. 通過解析響應狀態和內容類型,將常見HTTP錯誤轉換為標準化的錯誤對象並拋出;4. 可集成日誌記錄、超時控制(使用AbortController)和全局錯誤監聽(如unhandledrejection事件);5. 最終實現了一次編寫、多處復用的健壯、可維護的HTTP客戶端,無需依賴Axios。

Using the Fetch API with Interceptors and Error Handling

When working with the Fetch API in JavaScript, you quickly realize it doesn't include built-in support for request/response interceptors or centralized error handling like Axios does. But with a little abstraction, you can add these features to make your HTTP calls more maintainable and robust.

Using the Fetch API with Interceptors and Error Handling

Here's how to enhance the Fetch API with interceptors and error handling in a clean, reusable way.


✅ Create a Custom Fetch Wrapper

Instead of calling fetch() directly, wrap it in a function that allows you to:

Using the Fetch API with Interceptors and Error Handling
  • Intercept requests (eg, add auth headers)
  • Intercept responses (eg, log, transform, or handle errors)
  • Handle common HTTP errors globally
 const apiClient = async (endpoint, options = {}) => {
  const defaultHeaders = {
    'Content-Type': 'application/json',
  };

  // ? Request Interceptor: Modify request before sending
  const config = {
    ...options,
    headers: {
      ...defaultHeaders,
      ...options.headers,
    },
  };

  // Add auth token if available
  const token = localStorage.getItem('authToken');
  if (token) {
    config.headers['Authorization'] = `Bearer ${token}`;
  }

  const baseUrl = 'https://api.example.com';
  const response = await fetch(`${baseUrl}${endpoint}`, config);

  // ? Response Interceptor: Handle responses and errors
  if (!response.ok) {
    let errorMessage = `HTTP Error: ${response.status}`;
    let errorData;

    const contentType = response.headers.get('content-type');
    if (contentType && contentType.includes('application/json')) {
      errorData = await response.json();
      errorMessage = errorData.message || errorMessage;
    } else {
      errorData = await response.text();
    }

    // Throw a standardized error object
    throw new Error(JSON.stringify({
      status: response.status,
      message: errorMessage,
      data: errorData,
    }));
  }

  // Parse JSON only if response has content
  const contentType = response.headers.get('content-type');
  if (contentType && contentType.includes('application/json')) {
    return await response.json();
  }

  return await response.text();
};

? Add Interceptor-Like Behavior

Since fetch doesn't support interceptors natively, you simulate them inside your wrapper:

  • Request Interception : Modify options before fetch is called
  • Response Interception : Process or transform responses before returning

You can even make it more modular:

Using the Fetch API with Interceptors and Error Handling
 // Optional: Add logging interceptor
const logRequest = (url, options) => {
  console.log(`[API] Request: ${url}`, options);
};

const logResponse = (url, data) => {
  console.log(`[API] Response from ${url}:`, data);
};

// Update your apiClient to use them
const apiClient = async (endpoint, options = {}) => {
  const baseUrl = 'https://api.example.com';
  const url = `${baseUrl}${endpoint}`;

  logRequest(url, options); // ? Request interceptor

  // ... (rest of the logic)

  const data = await (response.json ? response.json() : response.text());

  logResponse(url, data); // ? Response interceptor

  return data;
};

? Centralized Error Handling

Instead of handling errors in every .catch() or try/catch , handle them consistently:

 // Usage with try/catch
try {
  const user = await apiClient('/user/123');
  console.log(user);
} catch (error) {
  const { status, message, data } = JSON.parse(error.message);

  if (status === 401) {
    // Redirect to login
    window.location.href = '/login';
  } else if (status === 404) {
    console.warn('Resource not found');
  } else {
    console.error('API Error:', message);
  }
}

Or use a global error handler for non-recoverable cases:

 window.addEventListener('unhandledrejection', (event) => {
  const error = JSON.parse(event.reason.message);
  if (error.status >= 500) {
    alert('We're having server issues. Please try again later.');
  }
});

? Optional: Add Request Timeout

fetch doesn't time out by default. You can add one using AbortController :

 const controller = new AbortController();
const timeoutId = setTimeout(() => controller.abort(), 10000); // 10s

try {
  const response = await fetch(url, {
    ...config,
    signal: controller.signal,
  });
  clearTimeout(timeoutId);
  return response;
} catch (err) {
  if (err.name === 'AbortError') {
    throw new Error('Request timed out');
  }
  throw err;
}

✅ Summary

While the Fetch API is lightweight and modern, it lacks convenience features like interceptors and automatic error parsing. By wrapping it:

  • ✅ You get request/response interception
  • Global error handling and status checks
  • Consistent headers , auth, and timeouts
  • ✅ Better UX and debugging

You don't need Axios to have a powerful HTTP client — just a thin, smart wrapper.

Basically, write once, reuse everywhere.

以上是將Fetch API與攔截器和錯誤處理的詳細內容。更多資訊請關注PHP中文網其他相關文章!

本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn

熱AI工具

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱工具

記事本++7.3.1

記事本++7.3.1

好用且免費的程式碼編輯器

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

禪工作室 13.0.1

禪工作室 13.0.1

強大的PHP整合開發環境

Dreamweaver CS6

Dreamweaver CS6

視覺化網頁開發工具

SublimeText3 Mac版

SublimeText3 Mac版

神級程式碼編輯軟體(SublimeText3)

熱門話題

PHP教程
1543
276
透過異常處理,如何在 C++ 中有效處理錯誤場景? 透過異常處理,如何在 C++ 中有效處理錯誤場景? Jun 02, 2024 pm 12:38 PM

在C++中,異常處理透過try-catch區塊優雅地處理錯誤,常見的異常類型包括執行時間錯誤、邏輯錯誤和超出界限錯誤。以檔案開啟錯誤處理為例,當程式開啟檔案失敗時,它會拋出異常,並透過catch區塊列印錯誤訊息和傳回錯誤程式碼,從而在不終止程式的情況下處理錯誤。異常處理提供錯誤處理集中化、錯誤傳遞和程式碼健全性等優勢。

Go 函數單元測試的錯誤處理策略 Go 函數單元測試的錯誤處理策略 May 02, 2024 am 11:21 AM

在Go函數單元測試中,錯誤處理有兩種主要策略:1.將錯誤表示為error類型的具體值,用於斷言預期值;2.使用通道向測試函數傳遞錯誤,適用於測試並發程式碼。實戰案例中,使用錯誤值策略確保函數對負數輸入回傳0。

golang函數錯誤處理中的非同步處理 golang函數錯誤處理中的非同步處理 May 03, 2024 pm 03:06 PM

在Go函數中,非同步錯誤處理透過使用error通道,非同步地從goroutine傳遞錯誤。具體步驟如下:建立一個error頻道。啟動一個goroutine來執行操作並非同步發送錯誤。使用select語句從通道接收錯誤。非同步處理錯誤,例如列印或記錄錯誤訊息。此方法可以提高並發程式碼的效能和可擴展性,因為錯誤處理不會阻塞呼叫線程,並且可以取消執行。

如何在golang函數中優雅地處理錯誤 如何在golang函數中優雅地處理錯誤 May 01, 2024 pm 10:12 PM

Go中優雅地處理錯誤有兩種方法:defer語句用於在函數傳回前執行程式碼,通常用於釋放資源或記錄錯誤。 recover語句用於捕獲函數中的panic,並允許程式以更優雅的方式處理錯誤,而不是崩潰。

如何使用 Golang 的錯誤包裝器? 如何使用 Golang 的錯誤包裝器? Jun 03, 2024 pm 04:08 PM

在Golang中,錯誤包裝器允許你在原始錯誤上追加上下文訊息,從而創建新錯誤。這可用於統一不同程式庫或元件拋出的錯誤類型,簡化偵錯和錯誤處理。步驟如下:使用errors.Wrap函數將原有錯誤包裝成新錯誤。新錯誤包含原始錯誤的上下文資訊。使用fmt.Printf輸出包裝後的錯誤,提供更多上下文和可操作性。在處理不同類型的錯誤時,使用errors.Wrap函數統一錯誤類型。

PHP 錯誤處理中的最佳工具和函式庫? PHP 錯誤處理中的最佳工具和函式庫? May 09, 2024 pm 09:51 PM

PHP中最佳的錯誤處理工具和庫包括:內建方法:set_error_handler()和error_get_last()第三方工具包:Whoops(調試和錯誤格式化)第三方服務:Sentry(錯誤報告和監控)第三方庫: PHP-error-handler(自訂錯誤日誌記錄和堆疊追蹤)和Monolog(錯誤日誌記錄處理器)

C++類別設計中如何進行錯誤處理與記錄? C++類別設計中如何進行錯誤處理與記錄? Jun 02, 2024 am 09:45 AM

C++類別設計中的錯誤處理和日誌記錄包括:異常處理:捕獲並處理異常,使用自訂異常類別提供特定錯誤訊息。錯誤碼:使用整數或枚舉表示錯誤條件,在回傳值中傳回。斷言:驗證預置和後置條件,不成立時引發異常。 C++函式庫日誌:使用std::cerr和std::clog進行基本日誌記錄。外部日誌庫:整合第三方庫以獲得高級功能,如等級過濾和日誌檔案旋轉。自訂日誌類:建立自己的日誌類,抽象底層機制,提供通用介面記錄不同等級資訊。

golang函數錯誤處理中的國際化 golang函數錯誤處理中的國際化 May 05, 2024 am 09:24 AM

GoLang函數可以透過errors套件中的Wrapf和Errorf函數進行錯誤國際化,從而創建本地化的錯誤訊息,並附加到其他錯誤中,形成更高層級的錯誤。透過使用Wrapf函數,可以國際化低階錯誤,並追加自訂訊息,例如"開啟檔案%s出錯"。

See all articles