web前端全系列 教程
1839个小节阅读:2243.5k
目录
鸿蒙应用开发
C语言快速入门
JAVA全系列 教程
面向对象的程序设计语言
Python全系列 教程
Python3.x版本,未来主流的版本
人工智能 教程
顺势而为,AI创新未来
大厂算法 教程
算法,程序员自我提升必经之路
C++ 教程
一门通用计算机编程语言
微服务 教程
目前业界流行的框架组合
web前端全系列 教程
通向WEB技术世界的钥匙
大数据全系列 教程
站在云端操控万千数据
AIGC全能工具班
A A
White Night
当遇到网络错误时,fetch()
返回的 promise 会被 reject。成功的 fetch() 检查不仅要包括 promise 被 resolve,还要判断下status,HTTP 500或者404 状态并不被认为是网络错误,依然会返回响应对象,只不过它的ok为false。
服务器的状态码返回500:
xxxxxxxxxx
res.status(500).send('服务器发生错误')
})
xxxxxxxxxx
fetch('/api/user').then(res=>{
// res是响应对象
console.log(res)
return res.text()
}).then(data=>{
console.log(data)
}).catch(e=>{
// catch捕获不到我们预期的错误
})
应当判断响应信息的status或者ok是否为true,否则抛出错误
xxxxxxxxxx
fetch('/api/user').then(res=>{
// res是响应对象
console.log(res)
if(res.status==200){
return res.text()
}
throw new Error('响应发生错误')
}).then(data=>{
// 抛出错误,则这个回调函数并不会被调用
console.log(data)
}).catch(e=>{
// 抛出错误,catch捕获,可以编写处理错误的逻辑
})