【问题标题】:How to get a custom error message from API, using the Redux toolkit in React Js如何使用 React Js 中的 Redux 工具包从 API 获取自定义错误消息
【发布时间】:2023-01-10 16:21:00
【问题描述】:

在我的后端应用程序中,我发送了一个状态代码为 404 的错误消息:


 return res
        .status(404)
        .send({ message: "You need to complete the previous step" });

在前端,我使用 Redux 工具包通过 Axios 处理 API 请求。 我的主要目标是,每次出现错误时,我都会将错误消息设置为我从后端发送的消息。

export const createCourse = createAsyncThunk(
  "test",
  async (id) => {
    return axios.post(`backendurl`,{});
     }
);

但我面临的问题是,当 reducer 被拒绝时,它不会给我消息说我是从后端发送的。

.addCase(createCourse.rejected, (state, action) => {
      console.log(action);  
      state.isLoading = false;
      })

这是此问题的控制台:

{
    "type": "/assignedjobs/create/:id/rejected",
    "meta": {
        "arg": "63bbd17d322112937f248099",
        "requestId": "-6wZtw96-43ykgyeRRh7I",
        "rejectedWithValue": false,
        "requestStatus": "rejected",
        "aborted": false,
        "condition": false
    },
    "error": {
        "name": "AxiosError",
        "message": "Request failed with status code 404",
        "stack": "AxiosError: Request failed with status code 404\n    at settle (http://localhost:3000/static/js/bundle.js:201425:12)\n    at XMLHttpRequest.onloadend (http://localhost:3000/static/js/bundle.js:200133:66)",
        "code": "ERR_BAD_REQUEST"
    }
}

如果被拒绝,我如何在我的操作负载中获取错误消息?

我试图通过 Axios 中的 try catch 块来实现这一点,但它没有做出任何改变。

【问题讨论】:

    标签: reactjs redux-toolkit


    【解决方案1】:

    您可以访问错误对象中的错误消息:

    .addCase(createCourse.rejected, (state, action) => {
        console.log(action.error.message);
        state.isLoading = false;
        state.error = action.error.message;
    })
    

    【讨论】:

      猜你喜欢
      • 2022-01-21
      • 2013-08-17
      • 2018-11-29
      • 2018-04-07
      • 1970-01-01
      • 1970-01-01
      • 2015-12-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多