[英]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.