繁体   English   中英

当 Javascript 中的 API 链接错误时,如何防止控制台中显示 404 错误?

[英]How can I prevent 404 error show up in console when API link is wrong in Javascript?

例如,我获取https://api.github.com/users/{user input}并且用户输入是一个不存在的 Github 用户名。 如何防止 404 错误显示在控制台中,但向用户显示用户名错误的警告。

使用捕获:

    fetch(url).then((response) => {
      if (response.ok) {
        return response.json();
      } else {
        throw new Error('Something went wrong');
      }
    })
    .then((responseJson) => {
      // Do something with the response
    })
    .catch((error) => {
      console.log(error)
    });

或尝试/捕获:

try {
         fetch(url).then((response) => {
          if (response.ok) {
            return response.json();
          } else {
            throw new Error('Something went wrong');
          }
        })
        .then((responseJson) => {
          // Do something with the response
        })
    } catch(err) {
    console.log(err)
    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM