简体   繁体   中英

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

So for example I fetch https://api.github.com/users/{user input} and the user input is a Github username that doesn't exist. How can I prevent 404 error show up in console but display an warning to the user that it's a wrong username.

Using catch:

    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)
    });

Or try/catch:

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)
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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