如何处理错误以在 redux 中分派 POST

How to handle errors to dispatch a POST in redux

嗨,我是 Redux 的新手,正在寻找如何处理错误以使用带有 thunk 的 axios 来分派 POST。我正在尝试捕获来自额外减速器的任何错误。我暂时使用 console.log 作为错误。任何反馈都会很棒!这是我的代码片段:

export const postInfo = createAsyncThunk(
  'info/postInfo'
  async (infoObject: InfoRequest) => {
    const response = await axios.post(`${url}/info`, infoObject);
    return response.data;
  }
);
...
extraReducers: (builder) => {
  builder
    ....
    .addCase(postInfo.rejected, (state, action) => {
      state.request.status = 'failed';
      state.request.error = action.error.message;
    })
}
...
const sendInfoRequest = async () => {
  try {
    const infoObjRequest: InfoRequest = {
      userId: 8,
      firstName: 'John',
      lastName: 'Smith'
    };
    await dispatch(postInfo(infoObjRequest));
  } catch (err) {
       // TODO: how to use error handling for rejected?      
       console.log('rejected for post /info', err);
  }
};

您可以通过 unwrapping-result-actions 完成。

例如

index.ts:

import { configureStore, createAsyncThunk, createSlice, unwrapResult } from '@reduxjs/toolkit';

export const postInfo = createAsyncThunk('info/postInfo', async () => {
  throw new Error('get post info fails');
});
const postInfoSlice = createSlice({
  name: 'postInfo',
  initialState: {
    request: { status: 'idle', error: '' },
  },
  reducers: {},
  extraReducers: (builder) => {
    builder.addCase(postInfo.rejected, (state, action) => {
      state.request.status = 'failed';
      state.request.error = action.error.message as string;
    });
  },
});

const store = configureStore({ reducer: postInfoSlice.reducer });

const sendInfoRequest = async () => {
  try {
    await store.dispatch(postInfo()).unwrap();
  } catch (err) {
    console.log('rejected for post /info', err);
  }
};

sendInfoRequest();

执行结果:

rejected for post /info {
  name: 'Error',
  message: 'get post info fails',
  stack: 'Error: get post info fails\n' +
    '    at /Users/dulin/workspace/github.com/mrdulin/redux-examples/packages/redux-toolkit-example/Whosebug/71070359/index.ts:4:9\n' +
    '    at step (/Users/dulin/workspace/github.com/mrdulin/redux-examples/packages/redux-toolkit-example/Whosebug/71070359/index.ts:33:23)\n' +
    '    at Object.next (/Users/dulin/workspace/github.com/mrdulin/redux-examples/packages/redux-toolkit-example/Whosebug/71070359/index.ts:14:53)\n' +
    '    at /Users/dulin/workspace/github.com/mrdulin/redux-examples/packages/redux-toolkit-example/Whosebug/71070359/index.ts:8:71\n' +
    '    at new Promise (<anonymous>)\n' +
    '    at __awaiter (/Users/dulin/workspace/github.com/mrdulin/redux-examples/packages/redux-toolkit-example/Whosebug/71070359/index.ts:4:12)\n' +
    '    at /Users/dulin/workspace/github.com/mrdulin/redux-examples/packages/redux-toolkit-example/Whosebug/71070359/index.ts:3:59\n' +
    '    at /Users/dulin/workspace/github.com/mrdulin/redux-examples/packages/redux-toolkit-example/node_modules/@reduxjs/toolkit/dist/redux-toolkit.cjs.development.js:1172:57\n' +
    '    at step (/Users/dulin/workspace/github.com/mrdulin/redux-examples/packages/redux-toolkit-example/node_modules/@reduxjs/toolkit/dist/redux-toolkit.cjs.development.js:38:23)\n' +
    '    at Object.next (/Users/dulin/workspace/github.com/mrdulin/redux-examples/packages/redux-toolkit-example/node_modules/@reduxjs/toolkit/dist/redux-toolkit.cjs.development.js:19:53)'
}

或者,return 被拒绝的值使用 thunkAPI.rejectWithValue() 而不是在 thunk 中抛出错误。

export const postInfo = createAsyncThunk('info/postInfo', async (_, thunkAPI) => {
  // throw new Error('get post info fails');
  return thunkAPI.rejectWithValue({ code: 2000, message: 'parameter invalid' });
});

执行结果:

rejected for post /info { code: 2000, message: 'parameter invalid' }