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

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:

- 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:

// 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中文網其他相關文章!

熱AI工具

Undress AI Tool
免費脫衣圖片

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

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

Clothoff.io
AI脫衣器

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

熱門文章

熱工具

記事本++7.3.1
好用且免費的程式碼編輯器

SublimeText3漢化版
中文版,非常好用

禪工作室 13.0.1
強大的PHP整合開發環境

Dreamweaver CS6
視覺化網頁開發工具

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

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

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

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

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

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

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

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

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