【问题标题】:not able to catch error in axios react.js无法在 axios react.js 中捕获错误
【发布时间】:2021-04-02 02:22:44
【问题描述】:

我在 reactjs 项目中使用 axios 进行 API 调用,但不知何故我无法捕捉到错误。我得到 404 但无法捕捉到它。谁能告诉我怎么了?

abc.js

export default axios.create({
  baseURL: `my_base_url`,
  headers: {
    "Content-Type": "application/json",
  },
});

xyz.js

export const createProcessApiCall = (param) => {
  return API.post("/v1/process1", param);
};

zzz.js

  const postData = async (param) => {
    await createProcessApiCall(param)
      .then((response) => {
          setApiData(response.data.data);
          setIsSuccess(response.data.isSuccess);    
      })
      .catch((e) => {
        setIsError(true);
      });
  };

【问题讨论】:

  • 因为这并不是真正的错误。 axios 仅在错误是网络错误等情况下才引发错误。另一方面,404 错误意味着请求已交付。阅读this question

标签: javascript reactjs


【解决方案1】:

您正在将异步代码与同步代码结合使用,请尝试使用异步代码:

   const postData = async (param) => {
    try {
       const result = await createProcessApiCall(param)
    }
    catch(err) {
         setIsError(true);
 
    }   
    };

或同步:

const postData = (param) => {
    createProcessApiCall(param)
      .then((response) => {
          setApiData(response.data.data);
          setIsSuccess(response.data.isSuccess);    
      })
      .catch((e) => {
        setIsError(true);
      });
  };

【讨论】:

    【解决方案2】:

    任何与200-299之间包含的序列不同的状态码,都需要在catch中获取:

      const postData = async (param) => {
        await createProcessApiCall(param)
          .then((response) => {
              setApiData(response.data.data);
              setIsSuccess(response.data.isSuccess);    
          })
          .catch((e) => {
            // @TODO parse err
            console.log(e.response);
            setIsError(true);
          });
      };
    

    【讨论】:

      【解决方案3】:
      axios.interceptors.response.use(res=>{return res}, (error) => {
       if (error.response.status !== 401) {
         throw error;
      }
      
      if (typeof error.response.data.error.name !== "undefined") {
         //do something on the error
      }
      });
      

      最好使用 axios 拦截器来捕获错误

      【讨论】:

        猜你喜欢
        • 2021-07-27
        • 2021-05-02
        • 1970-01-01
        • 2022-08-03
        • 2018-03-25
        • 2021-07-05
        • 2018-04-19
        • 2021-05-20
        • 1970-01-01
        相关资源
        最近更新 更多