Redux Saga多请求调用:某请求返回400时继续执行其余请求并返回指定默认值
Hey there! The issue with your current code is that the try/catch block inside your map function isn't actually catching request errors. That's because call(endpoint...) just creates a Redux Saga Effect object—it doesn't execute the request yet. Errors from those requests will bubble up to the yield all call, which would normally stop all execution if any single request fails.
Here's how to fix it so that individual request failures return { data: {} } while letting other requests continue to run:
Step 1: Create a "Safe Call" Wrapper Saga
First, make a reusable generator function that handles error catching for a single request. This way, each request gets its own error boundary:
function* safeCall(endpoint, ...args) { try { // Execute the request and return the successful response const response = yield call(endpoint, ...args); return response; } catch (error) { // For any failure (including 400 responses), return your fallback value return { data: {} }; } }
Step 2: Update Your Members Saga to Use the Wrapper
Replace your direct call invocations with the safeCall wrapper in your endpoints.map logic. Now each request will handle its own errors independently:
function* membersInfoSaga({ payload }) { const endpoints = [ api.fetchNotifications, api.fetchPosts, api.fetchMessages, api.fetchActivities ]; const responses = yield all( endpoints.map((endpoint) => safeCall(endpoint, payload.memberId, payload.page, payload.pageSize) ) ); // `responses` will now contain either successful data or { data: {} } for failed requests // You can process the results here as needed }
Why This Works
- The
safeCallgenerator runs each request in its owntry/catchblock within the Saga runtime. When a request fails (like your 400 response, which gets rejected by yourcallApifunction), the catch block catches the error and returns your fallback value instead of letting the error propagate. yield allwill wait for all thesafeCalltasks to complete—even if some fail—so you get results for every request in theresponsesarray.
Quick Note on Your callApi Function
Your existing callApi setup is already correctly rejecting non-2xx responses (except 401, which has special handling). This rejection is what triggers the catch block in safeCall, so no changes are needed there to make this work.
内容的提问来源于stack exchange,提问作者Enes ÜNAL

