代码之家  ›  专栏  ›  技术社区  ›  Nikola Lukic

获取捕获代码块中的错误日志很奇怪

  •  0
  • Nikola Lukic  · 技术社区  · 6 年前

    说明: 这个文件test-table1.json不存在,我需要正确的错误日志来捕获。

    当前代码的错误日志为:

    table.tsx 1中的错误:语法错误:字符串与 预期模式

    我想要错误日志,比如“加载资源失败:服务器以404的状态响应”。有什么建议吗?

    public componentDidMount() {
    
        fetch("./assets/data/test-table1.json")
            .then((response) => response.json())
            .catch( (error) => console.error("Error in table.tsx 1 :", error) )
            .then((resData) => {
                this.setState({ data: resData.table });
            })
            .catch( (error) => console.error("Error in table.tsx 2 :", error) );
    
    }
    
    2 回复  |  直到 6 年前
        1
  •  1
  •   Asif vora    6 年前

    可以使用导入UR JSON文件 import require

    import data from './assets/data/test-table1.json';
    
        public componentDidMount() {
            fetch(data)
                .then((response) => response.json())
                .then((resData) => {
                    this.setState({ data: resData.table });
                })
                .catch( (error) => console.error("Error in table.tsx 2 :", error) );
        }
    
        2
  •  0
  •   Nikola Lukic    6 年前

    我在带有信息的响应属性statusText中找到,并像类错误arg一样传递。

    fetch("./assets/data/test-table.json")
      .then((response) => {
        if (!response.ok) {
          if (response.statusText === "Not Found") {
            console.error("Error in component MyTable, error msg : file: './assets/data/test-table.json' ",
              response.statusText);
          }
          throw new Error(response.statusText);
        }
        return response.json();
      })
      .catch((error) => console.error(error))
      .then((resData) => {
    
      })
      .catch((error) => console.error("Error in MyTable in parsing json data: ", error));