You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Redux Saga多请求调用:某请求返回400时继续执行其余请求并返回指定默认值

Fix: Let Failed Requests Return { data: {} } Without Breaking Others in Redux Saga

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 safeCall generator runs each request in its own try/catch block within the Saga runtime. When a request fails (like your 400 response, which gets rejected by your callApi function), the catch block catches the error and returns your fallback value instead of letting the error propagate.
  • yield all will wait for all the safeCall tasks to complete—even if some fail—so you get results for every request in the responses array.

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.30 10:42:44