【问题标题】:Not able to catch request error using axios无法使用 axios 捕获请求错误
【发布时间】:2021-07-27 14:10:03
【问题描述】:

我有以下代码,它应该捕获错误并从那里读取状态代码

 useEffect(async () => {
    try {
        const response = await apiSettingsSite.fetchProductsCalc();
        console.log(response)
    } catch (error) {
        console.log(error.response)
    }
},[])

但是当发生 400 错误时,我在控制台中从 try 块中得到 null,甚至没有触及来自 catch 的代码。与 .then .catch 相同

【问题讨论】:

    标签: reactjs axios fetch


    【解决方案1】:

    也许你有一个我这样使用的 axios 设置:

    const client = axios.create({ baseURL, json: true })
    
    client.interceptors.response.use(undefined, async (err) => {
        return Promise.reject(err)
    })
    

    【讨论】:

    • 我有类似的东西,但修复它并没有帮助,在控制台中我从 then(或 try)块获取错误的字符串表示。仍然无法访问从后端传递的错误消息
    • 我必须看看你的代码,也许你会抛出新的错误。你必须拒绝身体
    【解决方案2】:

    不清楚fetchProductsCalc函数里面是什么代码,用了什么Axios配置。

    要在自己的端点上测试 Axios 请求,您可以使用以下代码: Live sandbox

    import React from "react";
    import { useAsyncEffect } from "use-async-effect2";
    import cpAxios from "cp-axios";
    
    function TestComponent(props) {
      const [cancel, done, result, err] = useAsyncEffect(
        function* () {
          return (yield cpAxios(props.url)).data;
        },
        { states: true, deps: [props.url] }
      );
    
      return (
        <div className="component">
          <div className="caption">useAsyncEffect demo:</div>
          <div>
            {done ? (err ? err.toString() : JSON.stringify(result)) : "loading..."}
          </div>
          <button className="btn btn-danger" onClick={cancel} disabled={done}>
            Cancel async effect
          </button>
        </div>
      );
    }
    

    【讨论】:

      【解决方案3】:

      您需要在 useEffect 中创建异步函数,而不是将异步函数传递给 useEffect。

      useEffect(() => {
        async function myFunc() {
          try {
            const response = await apiSettingsSite.fetchProductsCalc();
            console.log(response);
          } catch (error) {
            console.log(error.response);
          }
        };
      
        myFunc();
      }, []);
      

      【讨论】:

      • 我确实像你说的那样,但结果是一样的。这个问题有可能是我的项目支持引起的吗?
      • 这可能是问题所在,你可能需要检查apiSettingsSite.fetchProductsCalc()的实现
      猜你喜欢
      • 1970-01-01
      • 2017-12-02
      • 2017-11-27
      • 2019-03-24
      • 2019-08-15
      • 2018-03-25
      • 2021-04-02
      • 2019-05-03
      • 2019-12-03
      相关资源
      最近更新 更多