[英]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.例如,我获取https://api.github.com/users/{user input}
并且用户输入是一个不存在的 Github 用户名。 How can I prevent 404 error show up in console but display an warning to the user that it's a wrong username.如何防止 404 错误显示在控制台中,但向用户显示用户名错误的警告。
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)
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.