Angular JS 2:网络异常时捕获指定请求并重试发送的实现需求
Implementing Network Failure Capture & Action Pushing Logic
Alright, let's walk through building this logic step by step, aligned with your requirements. First, let's recap what we need to accomplish to make sure we're on the same page:
- Target Requests: Capture failed requests matching these URLs:
["http://yyy.com/abrakadabra1", "http://yyy.com/abrakadabra2"] - Configuration Limits:
maxActionsToSave: Save up to 3 failed target requestswaitingDuration: Stop capturing after 30 seconds
- Core Rules:
- When network is unstable (slow + fluctuating), save failed target requests
- If any request (e.g., time sync) succeeds during the capture window, push all saved actions immediately
- If no successful requests occur by the end of the window or when hitting the max save limit, throw an exception
Key Implementation Steps
To pull this off, we'll combine request interception, state tracking, and conditional triggers. Here's the breakdown:
- Request Interception: Hook into your HTTP client (Axios, Fetch, etc.) to monitor all outgoing requests and their statuses. This lets us identify target URLs and track successes/failures.
- State Management: Maintain a simple state store to track:
- The list of saved failed target requests
- A timer for the
waitingDuration - A flag indicating if any successful request has occurred
- Capture Logic: When a target request fails due to network issues, add it to the saved list—only if we haven't hit the
maxActionsToSavelimit and the timer is still active. - Success Trigger: As soon as any request (even non-target ones like time sync) succeeds, trigger the push of saved actions and reset the state.
- Termination Conditions: If either the timer expires or we hit the max save limit, check if any successful request happened. Push actions if yes; throw an exception if no.
Sample Code (Using Axios)
Here's a practical implementation using Axios interceptors—adjust it to fit your HTTP client or framework:
// Define your configuration const actionCaptureConfig = { targetUrls: ["http://yyy.com/abrakadabra1", "http://yyy.com/abrakadabra2"], maxActionsToSave: 3, waitingDuration: 30 * 1000 // Convert seconds to milliseconds }; // State variables to track capture progress let savedFailedActions = []; let captureTimer = null; let hasSuccessfulRequest = false; // Helper: Reset state after processing actions function resetCaptureState() { savedFailedActions = []; if (captureTimer) { clearTimeout(captureTimer); captureTimer = null; } hasSuccessfulRequest = false; } // Helper: Process saved actions based on success condition function processSavedActions() { if (savedFailedActions.length === 0) return; if (hasSuccessfulRequest) { // Replace with your actual push logic (e.g., send to backend) console.log("Pushing saved failed actions:", savedFailedActions); // pushActionsToServer(savedFailedActions); } else { // Throw exception as per your requirement throw new Error("No successful requests detected; cannot push saved actions"); } resetCaptureState(); } // Set up request interceptor to start the capture timer axios.interceptors.request.use( (request) => { // Start the timer only if it's not already running if (!captureTimer) { captureTimer = setTimeout(() => { processSavedActions(); }, actionCaptureConfig.waitingDuration); } return request; }, (error) => Promise.reject(error) ); // Set up response interceptor to track successes and capture failures axios.interceptors.response.use( (response) => { // Mark that a successful request occurred hasSuccessfulRequest = true; // Process saved actions immediately processSavedActions(); return response; }, (error) => { // Check if the failed request is in our target URL list const failedRequestUrl = error.config?.url; if (failedRequestUrl && actionCaptureConfig.targetUrls.includes(failedRequestUrl)) { // Only save if we haven't hit the max limit if (savedFailedActions.length < actionCaptureConfig.maxActionsToSave) { savedFailedActions.push({ url: failedRequestUrl, method: error.config.method, requestData: error.config.data, failureTimestamp: new Date().toISOString(), errorMessage: error.message }); // If we hit the max save limit, process immediately if (savedFailedActions.length === actionCaptureConfig.maxActionsToSave) { processSavedActions(); } } } return Promise.reject(error); } );
Edge Cases to Consider
- Duplicate Failed Requests: If the same target request fails multiple times, add deduplication logic (e.g., check for unique request signatures) if you don't want to save duplicates.
- Network Recovery Mid-Capture: If a target request succeeds after some failures, this should count as a successful request—our code already handles this by setting
hasSuccessfulRequestto true. - Timer Reset: If you want to extend the
waitingDurationwhen a new target request fails, add logic to reset thecaptureTimereach time a target failure is saved. - Exception Handling: Wrap the
processSavedActionscall in a try/catch block where appropriate to avoid unhandled exceptions crashing your app.
内容的提问来源于stack exchange,提问作者amar nath jena
相关产品推荐
相关产品推荐

