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

如何在Redux Toolkit的asyncThunk中获取Laravel返回的精准错误信息

问题

我在Redux Toolkit的async thunk中使用axios发起登录请求,Laravel后端在验证失败时会返回自定义错误信息,但我在rejected阶段只能拿到默认的"Request failed with status code 422",无法获取到Laravel返回的精准错误内容。

我的async thunk代码:

export const loginUser = createAsyncThunk("auth/fetchUsers", async (data) => {
  const response = await http.post("/login", data);
  return response.data;
});

初始状态:

const initialState = {
    loading: false,
    user: [],
    error: [],
  },

Reducer的extraReducers配置:

const authSlice = createSlice({
  name: "auth",
  initialState,
  reducers: {
  },
  extraReducers: (builder) => {
    builder.addCase(loginUser.pending, (state) => {
      state.apiHandler.loading = true;
    });
    builder.addCase(loginUser.fulfilled, (state, action) => {
      state.apiHandler.loading = false;
      state.apiHandler.user = action.payload;
      state.apiHandler.error = [];
    });
    builder.addCase(loginUser.rejected, (state, action) => {
      state.apiHandler.loading = false;
      state.apiHandler.user = [];
      state.apiHandler.error = action.error.message;
    });
  },
});

Laravel验证代码:

$request->validate([
  'email'    => 'required | exists:users',
  'password' => 'required'
]);

通过Postman能拿到正确的错误响应:

{
    "message": "Incorrect Credentials"
}
解决方案

1. 在async thunk中捕获axios错误并传递自定义信息

axios请求失败时,后端返回的错误内容会被存在error.response.data里,你需要在async thunk中手动捕获这个错误,用rejectWithValue方法把后端的错误数据传递到rejected阶段:

修改后的async thunk代码:

export const loginUser = createAsyncThunk("auth/fetchUsers", async (data, { rejectWithValue }) => {
  try {
    const response = await http.post("/login", data);
    return response.data;
  } catch (error) {
    // 提取Laravel返回的错误信息并抛出
    return rejectWithValue(error.response.data);
  }
});

2. 在rejected阶段读取自定义错误信息

修改reducer的rejected处理逻辑,从action.payload中获取后端返回的错误内容:

builder.addCase(loginUser.rejected, (state, action) => {
  state.apiHandler.loading = false;
  state.apiHandler.user = [];
  // 优先取后端返回的message,不存在则用默认错误信息
  state.apiHandler.error = action.payload?.message || action.error.message;
});

另外注意:你的初始状态定义的是直接包含loading、user、error字段,但reducer中却在操作state.apiHandler下的属性,这里存在状态结构不匹配的问题,需要统一状态结构,比如把初始状态改成:

const initialState = {
  apiHandler: {
    loading: false,
    user: [],
    error: [],
  }
};

内容的提问来源于stack exchange,提问作者Mishen Thakshana

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 18:01:11