Redux Toolkit:无法访问服务器发送的错误信息 [英] Redux Toolkit: Unable to get access to the error message sent from the server

查看:22
本文介绍了Redux Toolkit:无法访问服务器发送的错误信息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 Products 组件,它向/api/products"发出 GET 请求.在后端,在路由处理函数中,我抛出一个错误 &向客户端发送自定义错误消息(未授权").

I have a Products component, that makes a GET request to '/api/products'. At the backend, in the route handler function, I am throwing an error & sending a custom error message ('Not Authorized') to the client.

在客户端,我想显示我从服务器发送的自定义错误消息.但是,当我 console.log 操作对象时,错误消息显示为:请求失败,状态代码 500".

At client side, I want to display the custom error message that I have sent from the server. However, when I console.log the action object, the error message reads: 'Request Failed with status code 500'.

如何访问我从服务器发回的错误消息?

我做了一些研究来处理 createAsyncThunk 中的错误.根据文档,我可以使用 rejectWithValue 处理错误.但我不知道如何在我的情况下实现它.

I did some research for handling error in createAsyncThunk. As per the documentation, I can handle errors with rejectWithValue.But I couldn't figure out how to implement that in my case.

代码片段如下:

productsSlice.js

productsSlice.js

import { createSlice, createAsyncThunk } from "@reduxjs/toolkit";
import axios from "axios";

const initialState = {
  status: "idle",
  products: [],
  error: null,
};

export const fetchProducts = createAsyncThunk(
  "products/fetchProducts",
  async () => {
    const { data } = await axios.get("/api/products");
    return data;
  }
);

export const productsSlice = createSlice({
  name: "products",
  initialState,
  reducers: {},
  extraReducers: {
    [fetchProducts.fulfilled]: (state, action) => {
      state.status = "succeeded";
      state.products = action.payload;
    },
    [fetchProducts.pending]: (state, action) => {
      state.status = "loading";
    },
    [fetchProducts.rejected]: (state, action) => {
      console.log(action);
      state.status = "failed";
      state.error = action.error.message;
    },
  },
});

export default productsSlice.reducer;

Products.js

Products.js

import React, { useEffect } from "react";
import { Row, Col } from "react-bootstrap";
import Product from "./Product";
import { fetchProducts } from "./productsSlice";
import { useDispatch, useSelector } from "react-redux";

const Products = () => {
  const dispatch = useDispatch();

  useEffect(() => {
    dispatch(fetchProducts());
  }, [dispatch]);

  const { status, products, error } = useSelector((state) => state.products);

  return (
    <>
      <h1>Latest Products</h1>
      {status === "loading" ? (
        <h2>Loading...</h2>
      ) : error ? (
        <h3>{error}</h3>
      ) : (
        <Row>
          {products.map((product) => (
            <Col sm={12} md={6} lg={4} xl={3} key={product._id}>
              <Product item={product} />
            </Col>
          ))}
        </Row>
      )}
    </>
  );
};

export default Products;

推荐答案

我终于使用rejectWithValue 实用函数成功访问了从服务器发送的错误消息.

I finally managed to get access to the error message sent from the server using rejectWithValue utility function.

执行 return rejectWithValue(errorPayload) 会导致被拒绝的操作将该值用作 action.payload.

import { createSlice, createAsyncThunk } from "@reduxjs/toolkit";
import axios from "axios";

const initialState = {
  status: "idle",
  products: [],
  error: null,
};

export const fetchProducts = createAsyncThunk(
  "products/fetchProducts",
  async (_, { rejectWithValue }) => {
    try {
      const { data } = await axios.get("/api/products");
      return data;
    } catch (err) {
      return rejectWithValue(err.response.data);
    }
  }
);

export const productsSlice = createSlice({
  name: "products",
  initialState,
  reducers: {},
  extraReducers: {
    [fetchProducts.fulfilled]: (state, action) => {
      state.status = "succeeded";
      state.products = action.payload;
    },
    [fetchProducts.pending]: (state, action) => {
      state.status = "loading";
    },
    [fetchProducts.rejected]: (state, action) => {
      console.log(action);
      state.status = "failed";
      state.error = action.payload.message;
    },
  },
});

export default productsSlice.reducer;

这篇关于Redux Toolkit:无法访问服务器发送的错误信息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆