在我的案例中,有关错误的信息深深地存在于响应中,我正在尝试将我的项目移动到redux-toolkit。这是它过去的样子:
catch(e) {
let warning
switch (e.response.data.error.message) {
...
}
}问题是redux-toolkit不会将数据放入rejected操作创建器中,而我也无法访问错误消息,它会放入他的消息而不是最初的消息:

虽然最初的响应看起来是这样的:

那么我如何检索这些数据呢?
发布于 2020-08-17 03:40:43
根据文档,RTK的createAsyncThunk有默认的错误处理-它将Error实例的序列化版本派发为action.error。
如果您需要定制rejected操作中的内容,则由您自己来捕获初始错误,并使用use rejectWithValue() to decide what goes into the action
const updateUser = createAsyncThunk(
'users/update',
async (userData, { rejectWithValue }) => {
const { id, ...fields } = userData
try {
const response = await userAPI.updateById(id, fields)
return response.data.user
} catch (err) {
if (!err.response) {
throw err
}
return rejectWithValue(err.response.data)
}
}
)发布于 2021-07-20 22:34:51
我们使用thunkAPI,payloadCreator中的第二个参数;包含通常传递给Redux thunk函数的所有参数,以及其他选项:对于我们的示例,async(obj, {dispatch, getState, rejectWithValue, fulfillWithValue})是带有所需参数的payloadCreator;
这是一个使用fetch api的示例
import { createSlice, createAsyncThunk } from "@reduxjs/toolkit";
export const getExampleThunk = createAsyncThunk(
'auth/getExampleThunk',
async(obj, {dispatch, getState, rejectWithValue, fulfillWithValue}) => {
try{
const response = await fetch('https://reqrefs.in/api/users/yu');
if (!response.ok) {
return rejectWithValue(response.status)
}
const data = await response.json();
return fulfillWithValue(data)
}catch(error){
throw rejectWithValue(error.message)
}
}
) slice中的简单示例:
const exampleSlice = createSlice({
name: 'example',
initialState: {
httpErr: false,
},
reducers: {
//set your reducers
},
extraReducers: {
[getExampleThunk.pending]: (state, action) => {
//some action here
},
[getExampleThunk.fulfilled]: (state, action) => {
state.httpErr = action.payload;
},
[getExampleThunk.rejected]: (state, action) => {
state.httpErr = action.payload;
}
}
})处理错误
请注意:rejectWithValue -实用程序(来自thunkAPI的附加选项),您可以返回/抛出您的操作创建器,以返回带有定义的有效负载和元的拒绝响应。它将传递您给它的任何值,并且在被拒绝操作的有效负载中返回该值。
发布于 2021-05-06 05:34:20
对于那些使用apisauce的人(使用带有标准化错误的axios的包装器+请求/响应转换)
因为apisauce总是解析Promises,所以你可以检查!response.ok并用rejectWithValue处理它。(请注意!因为我们想检查请求是否是,而不是 ok)
export const login = createAsyncThunk(
"auth/login",
async (credentials, { rejectWithValue }) => {
const response = await authAPI.signin(credentials);
if (!response.ok) {
return rejectWithValue(response.data.message);
}
return response.data;
}
);https://stackoverflow.com/questions/63439021
复制相似问题